Esempio n. 1
0
  private static Map<String, Class<?>> defineClasses(
      List<ClassDefinition> classDefinitions, DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader =
        ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DumpByteCodeVisitor dumpByteCode = new DumpByteCodeVisitor(new PrintStream(out));
      for (ClassDefinition classDefinition : classDefinitions) {
        dumpByteCode.visitClass(classDefinition);
      }
      System.out.println(new String(out.toByteArray(), StandardCharsets.UTF_8));
    }

    Map<String, byte[]> byteCodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
      ClassWriter cw = new SmartClassWriter(classInfoLoader);
      classDefinition.visit(cw);
      byte[] byteCode = cw.toByteArray();
      if (RUN_ASM_VERIFIER) {
        ClassReader reader = new ClassReader(byteCode);
        CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
      }
      byteCodes.put(classDefinition.getType().getJavaClassName(), byteCode);
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
      for (Map.Entry<String, byte[]> entry : byteCodes.entrySet()) {
        File file =
            new File(
                dumpClassPath,
                ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
        try {
          log.debug("ClassFile: " + file.getAbsolutePath());
          Files.createParentDirs(file);
          Files.write(entry.getValue(), file);
        } catch (IOException e) {
          log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
        }
      }
    }
    if (DUMP_BYTE_CODE_RAW) {
      for (byte[] byteCode : byteCodes.values()) {
        ClassReader classReader = new ClassReader(byteCode);
        classReader.accept(
            new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.SKIP_FRAMES);
      }
    }
    Map<String, Class<?>> classes = classLoader.defineClasses(byteCodes);
    try {
      for (Class<?> clazz : classes.values()) {
        Reflection.initialize(clazz);
      }
    } catch (VerifyError e) {
      throw new RuntimeException(e);
    }
    return classes;
  }
Esempio n. 2
0
  // guava会过滤掉hashCode、toString、equals方法的代理
  @Test
  public void testGuavaProxy() {
    IFoo real =
        new IFoo() {
          @Override
          public void doSomething() {
            System.out.println("hello");
          }
        };
    IFoo foo = Reflection.newProxy(IFoo.class, new MyInvocationHandler(real));
    System.out.println("jdk InvocationHandler");
    foo.doSomething();
    System.out.println(foo);
    System.out.println("--------------------");

    IFoo foo2 = Reflection.newProxy(IFoo.class, new GuavaInvocationHandler(real));
    System.out.println("guava AbstractInvocationHandler");
    foo2.doSomething();
    System.out.println(foo2);
    System.out.println("--------------------");

    IFoo foo3 = Reflection.newProxy(IFoo.class, new GuavaInvocationHandler(real));
    System.out.println(foo2.equals(foo3));
  }
Esempio n. 3
0
  private Api newProxyWrapper() {
    Api backend = newRestAdapter();
    // proxy to add the nonce if not provided
    return Reflection.newProxy(
        Api.class,
        (proxy, method, args) -> {
          Class<?>[] params = method.getParameterTypes();
          if (params.length > 0 && params[0] == Api.Nonce.class) {
            if (args.length > 0 && args[0] == null) {

              // inform about failure.
              try {
                args = Arrays.copyOf(args, args.length);
                args[0] = cookieHandler.getNonce();

              } catch (Throwable error) {
                AndroidUtility.logToCrashlytics(error);

                if (method.getReturnType() == Observable.class) {
                  // don't fail here, but fail in the resulting observable.
                  return Observable.error(error);

                } else {
                  throw error;
                }
              }
            }
          }

          if (method.getReturnType() == Observable.class) {
            // check if this is a get for retry.
            int retryCount = 2;
            if (method.getAnnotation(GET.class) != null) {
              return invokeWithRetry(backend, method, args, ApiProvider::isHttpError, retryCount);
            } else {
              return invokeWithRetry(backend, method, args, ApiProvider::isHttpError, retryCount);
            }
          }

          try {
            return method.invoke(backend, args);
          } catch (InvocationTargetException targetError) {
            throw targetError.getCause();
          }
        });
  }
  @Test
  public void onCreateService_whenDuplicateMethodNames_shouldThrowException() throws Exception {
    Session session = new Session.Builder().setCredential(credential).build();

    RestAdapter restAdapter = mock(RestAdapter.class);

    DuplicateNameUberApiService service =
        Reflection.newProxy(
            DuplicateNameUberApiService.class,
            new RetrofitUberRidesClient.InvocationHandler<>(
                session.getEnvironment(), DuplicateNameUberApiService.class, restAdapter));

    exception.expect(IllegalStateException.class);
    exception.expectMessage("Services may not contain duplicate names.");

    Callback<Void> callback = mock(Callback.class);

    service.duplicateMethod("thisIsNotAProductId", callback);
  }
Esempio n. 5
0
 /** Try to find all implementation classes of {@link Allocator} in the same package. */
 @Before
 @Override
 public void before() throws Exception {
   super.before();
   mStrategies = new ArrayList<>();
   try {
     String packageName = Reflection.getPackageName(Allocator.class);
     ClassPath path = ClassPath.from(Thread.currentThread().getContextClassLoader());
     List<ClassPath.ClassInfo> clazzInPackage =
         new ArrayList<>(path.getTopLevelClassesRecursive(packageName));
     for (ClassPath.ClassInfo clazz : clazzInPackage) {
       Set<Class<?>> interfaces = new HashSet<>(Arrays.asList(clazz.load().getInterfaces()));
       if (interfaces.size() > 0 && interfaces.contains(Allocator.class)) {
         mStrategies.add(clazz.getName());
       }
     }
   } catch (Exception e) {
     Assert.fail("Failed to find implementation of allocate strategy");
   }
 }
@RunWith(MockitoJUnitRunner.class)
public class SasLogicalInterconnectGroupClientTest {

  private static final String ANY_RESOURCE_ID = "random-UUID";
  private static final String ANY_RESOURCE_NAME = "random-Name";

  private BaseClient baseClient = mock(BaseClient.class);
  private SasLogicalInterconnectGroupClient client =
      Reflection.newProxy(
          SasLogicalInterconnectGroupClient.class,
          new ClientRequestHandler<>(baseClient, SasLogicalInterconnectGroupClient.class));

  @Test
  public void shouldGetSasLogicalInterconnectGroupById() {
    client.getById(ANY_RESOURCE_ID);

    String expectedUri = SAS_LOGICAL_INTERCONNECT_GROUP_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

    then(baseClient)
        .should()
        .executeRequest(expectedRequest, TypeToken.of(SasLogicalInterconnectGroup.class).getType());
  }

  @Test
  public void shouldGetAllSasLogicalInterconnectGroups() {
    given(this.baseClient.executeRequest(any(Request.class), any(Type.class)))
        .willReturn(new ResourceCollection<>());

    client.getAll();

    Request expectedRequest = new Request(HttpMethod.GET, SAS_LOGICAL_INTERCONNECT_GROUP_URI);

    then(baseClient)
        .should()
        .executeRequest(
            expectedRequest,
            new TypeToken<ResourceCollection<SasLogicalInterconnectGroup>>() {}.getType());
  }

  @Test
  public void shouldGetSasLogicalInterconnectGroupsByName() {
    client.getByName(ANY_RESOURCE_NAME);

    Request expectedRequest = new Request(HttpMethod.GET, SAS_LOGICAL_INTERCONNECT_GROUP_URI);
    expectedRequest.addQuery(UrlParameter.getFilterByNameParameter(ANY_RESOURCE_NAME));

    then(baseClient)
        .should()
        .executeRequest(
            expectedRequest,
            new TypeToken<ResourceCollection<SasLogicalInterconnectGroup>>() {}.getType());
  }

  @Test
  public void shouldCreateSasLogicalInterconnectGroup() {
    SasLogicalInterconnectGroup group = new SasLogicalInterconnectGroup();

    client.create(group, TaskTimeout.of(321));
    Request expectedRequest =
        new Request(HttpMethod.POST, SAS_LOGICAL_INTERCONNECT_GROUP_URI, group);
    expectedRequest.setTimeout(321);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldUpdateSasLogicalInterconnectGroup() {
    SasLogicalInterconnectGroup group = new SasLogicalInterconnectGroup();

    client.update(ANY_RESOURCE_ID, group, TaskTimeout.of(321));

    String expectedUri = SAS_LOGICAL_INTERCONNECT_GROUP_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.PUT, expectedUri, group);
    expectedRequest.setTimeout(321);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldDeleteSasLogicalInterconnectGroup() {
    client.delete(ANY_RESOURCE_ID, TaskTimeout.of(321));

    String expectedUri = SAS_LOGICAL_INTERCONNECT_GROUP_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.DELETE, expectedUri);
    expectedRequest.setTimeout(321);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }
}
@RunWith(MockitoJUnitRunner.class)
public class ArtifactsBundleClientTest {

  private static final String ANY_RESOURCE_ID = "random-UUID";
  private static final String ANY_RESOURCE_NAME = "random-Name";
  private static final String ANY_FILE_PATH = "random-file-path";
  private static final String ANY_TASK_URI = "/rest/tasks/4545db75-1861-45a2-8468-f11ff07381rf";
  private static final String DEPLOYMENT_GROUP_RESOURCE_ID = "40ca28c0-d7cd-4312-be24-46f57e5737e4";

  private BaseClient baseClient = mock(BaseClient.class);
  private ArtifactsBundleClient client =
      Reflection.newProxy(
          ArtifactsBundleClient.class,
          new ClientRequestHandler<>(baseClient, ArtifactsBundleClient.class));

  @Test
  public void shouldGetArtifactsBundle() {
    client.getById(ANY_RESOURCE_ID);

    String expectedUri = ARTIFACTS_BUNDLE_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

    then(baseClient)
        .should()
        .executeRequest(expectedRequest, TypeToken.of(ArtifactsBundle.class).getType());
  }

  @Test
  public void shouldGetAllArtifactsBundles() {
    given(this.baseClient.executeRequest(any(Request.class), any(Type.class)))
        .willReturn(new ResourceCollection<>());

    client.getAll();

    Request expectedRequest = new Request(HttpMethod.GET, ARTIFACTS_BUNDLE_URI);

    then(baseClient)
        .should()
        .executeRequest(
            expectedRequest, new TypeToken<ResourceCollection<ArtifactsBundle>>() {}.getType());
  }

  @Test
  public void shouldGetArtifactsBundleCollectionByName() {
    client.getByName(ANY_RESOURCE_NAME);

    Request expectedRequest = new Request(HttpMethod.GET, ARTIFACTS_BUNDLE_URI);
    expectedRequest.addQuery(UrlParameter.getFilterByNameParameter(ANY_RESOURCE_NAME));

    then(baseClient)
        .should()
        .executeRequest(
            expectedRequest, new TypeToken<ResourceCollection<ArtifactsBundle>>() {}.getType());
  }

  @Test
  public void shouldCreateArtifactsBundle() {
    CreateArtifactsBundle artifactsBundle = new CreateArtifactsBundle();

    client.create(artifactsBundle, TaskTimeout.of(123));

    Request expectedRequest = new Request(HttpMethod.POST, ARTIFACTS_BUNDLE_URI, artifactsBundle);
    expectedRequest.setTimeout(123);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldCreateArtifactsBundleFromFile() {
    File file = new File(ANY_FILE_PATH);
    client.create(file, DownloadPath.at(ANY_FILE_PATH));

    Request expectedRequest = new Request(HttpMethod.POST, ARTIFACTS_BUNDLE_URI, file);
    expectedRequest.setDownloadPath(ANY_FILE_PATH);
    expectedRequest.setContentType(ContentType.MULTIPART_FORM_DATA);
    expectedRequest.setForceReturnTask(true);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldGetBackupBundles() {
    client.getBackupBundles();

    String expectedUri = ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_BACKUPS_URI;
    Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

    then(baseClient)
        .should()
        .executeRequest(
            expectedRequest, new TypeToken<ResourceCollection<ArtifactsBundle>>() {}.getType());
  }

  @Test
  public void shouldCreateBackupBundle() {
    UserBackupParams userBackupParams = new UserBackupParams();

    client.createBackupBundle(userBackupParams, TaskTimeout.of(123));
    String expectedUri = ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_BACKUPS_URI;
    Request expectedRequest = new Request(HttpMethod.POST, expectedUri, userBackupParams);
    expectedRequest.setTimeout(123);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldCreateBackupArchiveBundle() {
    File file = new File(ANY_FILE_PATH);

    String deploymentGrpUri =
        DeploymentGroupClient.DEPLOYMENT_GROUP_URI + "/" + DEPLOYMENT_GROUP_RESOURCE_ID;
    UrlParameter query = new UrlParameter("deploymentGrpUri", deploymentGrpUri);
    client.createBackupArchiveBundle(file, deploymentGrpUri, DownloadPath.at(ANY_FILE_PATH));

    String expectedUri =
        ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_BACKUPS_URI + ARTIFACTS_BUNDLE_ARCHIVE_URI;

    Request expectedRequest = new Request(HttpMethod.POST, expectedUri, file);
    expectedRequest.addQuery(query);
    expectedRequest.setDownloadPath(ANY_FILE_PATH);
    expectedRequest.setContentType(ContentType.MULTIPART_FORM_DATA);
    expectedRequest.setForceReturnTask(true);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldGetBackupArchiveBundle() {
    client.downloadBackupArchiveBundle(ANY_RESOURCE_ID);

    String expectedUri =
        ARTIFACTS_BUNDLE_URI
            + ARTIFACTS_BUNDLE_BACKUPS_URI
            + ARTIFACTS_BUNDLE_ARCHIVE_URI
            + "/"
            + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

    then(baseClient).should().executeRequest(expectedRequest, TypeToken.of(String.class).getType());
  }

  @Test
  public void shouldGetBackupBundle() {
    client.getBackupBundle(ANY_RESOURCE_ID);

    String expectedUri =
        ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_BACKUPS_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

    then(baseClient)
        .should()
        .executeRequest(expectedRequest, TypeToken.of(ArtifactsBundle.class).getType());
  }

  @Test
  public void shouldExtractBackupBundle() {
    UserBackupParams userBackupParams = new UserBackupParams();
    client.extractBackupBundle(ANY_RESOURCE_ID, userBackupParams, TaskTimeout.of(123));

    String expectedUri =
        ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_BACKUPS_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.PUT, expectedUri, userBackupParams);
    expectedRequest.setTimeout(123);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldDownloadBundle() {
    client.downloadBundle(ANY_RESOURCE_ID);

    String expectedUri =
        ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_DOWNLOAD_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

    then(baseClient).should().executeRequest(expectedRequest, TypeToken.of(String.class).getType());
  }

  @Test
  public void shouldExtractBundle() {
    client.extractBundle(ANY_RESOURCE_ID, TaskTimeout.of(123));

    String expectedUri = ARTIFACTS_BUNDLE_URI + "/" + ANY_RESOURCE_ID;
    Request expectedRequest = new Request(HttpMethod.PUT, expectedUri, "");
    expectedRequest.setContentType(ContentType.TEXT_PLAIN);
    expectedRequest.setTimeout(123);

    then(baseClient).should().executeMonitorableRequest(expectedRequest);
  }

  @Test
  public void shouldStopBundleCreation() {
    TaskUri taskUri = new TaskUri();

    taskUri.setTaskUri(ANY_TASK_URI);

    client.stopBundleCreation(ANY_RESOURCE_ID, taskUri);

    String expectedUri =
        ARTIFACTS_BUNDLE_URI + "/" + ANY_RESOURCE_ID + ARTIFACTS_BUNDLE_STOP_ARTIFACT_CREATE_URI;
    Request expectedRequest = new Request(HttpMethod.PUT, expectedUri, taskUri);

    then(baseClient).should().executeRequest(expectedRequest, TypeToken.of(String.class).getType());
  }
}