Пример #1
0
  @Test
  public void nestedSelfRefsInStringContentWithoutParentFile()
      throws NoSuchMethodException, ClassNotFoundException, IOException {

    String schemaContents =
        IOUtils.toString(
            CodeGenerationHelper.class.getResource("/schema/ref/nestedSelfRefsReadAsString.json"));
    JCodeModel codeModel = new JCodeModel();
    new SchemaMapper().generate(codeModel, "NestedSelfRefsInString", "com.example", schemaContents);

    codeModel.build(schemaRule.getGenerateDir());

    ClassLoader classLoader = schemaRule.compile();

    Class<?> nestedSelfRefs = classLoader.loadClass("com.example.NestedSelfRefsInString");
    assertThat(
        nestedSelfRefs.getMethod("getThings").getReturnType().getSimpleName(), equalTo("List"));

    Class<?> listEntryType =
        (Class<?>)
            ((ParameterizedType) nestedSelfRefs.getMethod("getThings").getGenericReturnType())
                .getActualTypeArguments()[0];
    assertThat(listEntryType.getName(), equalTo("com.example.Thing"));

    Class<?> thingClass = classLoader.loadClass("com.example.Thing");
    assertThat(
        thingClass.getMethod("getNamespace").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(thingClass.getMethod("getName").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(
        thingClass.getMethod("getVersion").getReturnType().getSimpleName(), equalTo("String"));
  }
  @Before
  public void resetIndividualClassLoader() throws Exception {
    sharedCache = new IndividualClassLoader.Cache();
    l1 = new IndividualClassLoader("instrumentertest", sharedCache);
    l2 = new IndividualClassLoader("instrumentertest", sharedCache);

    // Set up noop RobotMonitors.

    SandboxedRobotPlayer.Pauser pauser = () -> {};
    SandboxedRobotPlayer.Killer killer = () -> {};

    final Class<?> monitor1 = l1.loadClass("battlecode.instrumenter.inject.RobotMonitor");
    monitor1
        .getMethod(
            "init", SandboxedRobotPlayer.Pauser.class, SandboxedRobotPlayer.Killer.class, int.class)
        .invoke(null, pauser, killer, 0);
    monitor1.getMethod("setBytecodeLimit", int.class).invoke(null, Integer.MAX_VALUE);

    final Class<?> monitor2 = l2.loadClass("battlecode.instrumenter.inject.RobotMonitor");
    monitor2
        .getMethod(
            "init", SandboxedRobotPlayer.Pauser.class, SandboxedRobotPlayer.Killer.class, int.class)
        .invoke(null, pauser, killer, 0);
    monitor2.getMethod("setBytecodeLimit", int.class).invoke(null, Integer.MAX_VALUE);
  }
Пример #3
0
  @Test
  public void testAddGetter() throws Exception {
    final TestClassLoader loader = getTestClassLoader();
    final String targetClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject3";

    loader.addTransformer(
        targetClassName,
        new TransformCallback() {

          @Override
          public byte[] doInTransform(
              Instrumentor instrumentContext,
              ClassLoader classLoader,
              String className,
              Class<?> classBeingRedefined,
              ProtectionDomain protectionDomain,
              byte[] classfileBuffer)
              throws InstrumentException {
            try {
              logger.info("modify cl:{}", classLoader);
              InstrumentClass aClass =
                  instrumentContext.getInstrumentClass(classLoader, className, classfileBuffer);

              aClass.addGetter(StringGetter.class.getName(), "value");
              aClass.addGetter(IntGetter.class.getName(), "intValue");

              return aClass.toBytecode();
            } catch (InstrumentException e) {
              throw new RuntimeException(e.getMessage(), e);
            }
          }
        });

    loader.initialize();

    Object testObject = loader.loadClass(targetClassName).newInstance();

    Class<?> stringGetter = loader.loadClass(StringGetter.class.getName());
    Class<?> intGetter = loader.loadClass(IntGetter.class.getName());

    Assert.assertTrue(stringGetter.isInstance(testObject));
    Assert.assertTrue(intGetter.isInstance(testObject));

    String value = "hehe";
    int intValue = 99;

    Method method = testObject.getClass().getMethod("setValue", String.class);
    method.invoke(testObject, value);

    Method getString = stringGetter.getMethod("_$PINPOINT$_getString");
    Assert.assertEquals(value, getString.invoke(testObject));

    Method setIntValue = testObject.getClass().getMethod("setIntValue", int.class);
    setIntValue.invoke(testObject, intValue);

    Method getInt = intGetter.getMethod("_$PINPOINT$_getInt");
    Assert.assertEquals(intValue, getInt.invoke(testObject));
  }
  @Test
  public void detectsMethodsOnPagingAndSortingRepository() throws Exception {

    Class<DomainPagingAndSortingRepository> type = DomainPagingAndSortingRepository.class;

    assertFindAllMethodOn(type, type.getMethod("findAll", Pageable.class));
    assertDeleteMethodOn(type, type.getMethod("delete", Serializable.class));
    assertSaveMethodPresent(type, true);
  }
  @Test
  public void detectsMethodsOnCustomRepository() throws Exception {

    Class<RepositoryWithCustomSortingAndPagingFindAll> type =
        RepositoryWithCustomSortingAndPagingFindAll.class;
    assertFindAllMethodOn(type, type.getMethod("findAll", Pageable.class));

    Class<RepositoryWithIterableDeleteOnly> type1 = RepositoryWithIterableDeleteOnly.class;
    assertDeleteMethodOn(type1, type1.getMethod("delete", Iterable.class));
  }
Пример #6
0
  @Test
  public void testClassWrapper() throws Exception {
    Calc calc = new CalcImpl();

    WrapperProxetta proxetta =
        WrapperProxetta.withAspects(
            new ProxyAspect(
                StatCounterAdvice.class,
                new ProxyPointcutSupport() {
                  public boolean apply(MethodInfo methodInfo) {
                    return !isRootMethod(methodInfo) && isPublic(methodInfo);
                  }
                }));

    //		proxetta.setDebugFolder("d:\\");

    // wrapper over CLASS
    // resulting object has ALL interfaces
    // resulting object wraps ALL target class methods
    WrapperProxettaBuilder builder = proxetta.builder(calc.getClass());

    Class calc2Class = builder.define();

    Object object = calc2Class.newInstance();

    assertTrue(object instanceof Calc);
    assertEquals(CalcImpl.class, ProxettaUtil.getTargetClass(object.getClass()));
    assertEquals(1, calc2Class.getInterfaces().length);

    builder.injectTargetIntoWrapper(calc, object);

    assertEquals(1, StatCounter.counter); // counter in static block !!!

    Method method = calc2Class.getMethod("hello");
    assertNotNull(method);
    method.invoke(object);

    assertEquals(2, StatCounter.counter);

    method = calc2Class.getMethod("calculate", int.class, int.class);
    assertNotNull(method);
    Integer result = (Integer) method.invoke(object, 3, 7);
    assertEquals(10, result.intValue());

    assertEquals(3, StatCounter.counter);

    assertNotNull(calc2Class.getMethod("customMethod"));
  }
Пример #7
0
  @Test
  public void selfRefUsedInAPropertyIsReadSuccessfully() throws NoSuchMethodException {

    Class<?> aClass = selfRefsClass.getMethod("getChildOfSelf").getReturnType();

    assertThat(aClass.getName(), is("com.example.SelfRefs"));
  }
  @Test
  public void refToFragmentOfAnotherSchemaIsReadSuccessfully() throws NoSuchMethodException {

    Class<?> aClass = fragmentRefsClass.getMethod("getFragmentOfA").getReturnType();

    assertThat(aClass.getName(), is("com.example.AdditionalPropertyValue"));
  }
Пример #9
0
  private void verifyTopDownItem(PN parentNode) throws Exception {
    Method getItemMethod = parentNodeClass.getMethod(itemMethodName);
    @SuppressWarnings("unchecked")
    CN childNode = (CN) getItemMethod.invoke(parentNode);

    assertEquals(childPath.getAbsolutePath(), childNode.dir().getPath());
  }
Пример #10
0
  @Test
  public void refToFragmentOfSelfIsReadSuccessfully() throws NoSuchMethodException {

    Class<?> aClass = fragmentRefsClass.getMethod("getFragmentOfSelf").getReturnType();

    assertThat(aClass.getName(), is("com.example.A"));
    assertThat(aClass.getMethods(), hasItemInArray(hasProperty("name", equalTo("getPropertyOfA"))));
  }
  @Test
  public void detectsFindAllWithSortParameterOnSortingRepository() throws Exception {

    Class<RepositoryWithCustomSortingFindAll> type = RepositoryWithCustomSortingFindAll.class;

    assertFindAllMethodOn(type, type.getMethod("findAll", Sort.class));
    assertSaveMethodPresent(type, false);
  }
Пример #12
0
  @Test
  public void selfRefUsedAsArrayItemsIsReadSuccessfully() throws NoSuchMethodException {

    Type listOfAType = selfRefsClass.getMethod("getArrayOfSelf").getGenericReturnType();
    Class<?> listEntryClass =
        (Class<?>) ((ParameterizedType) listOfAType).getActualTypeArguments()[0];

    assertThat(listEntryClass.getName(), is("com.example.SelfRefs"));
  }
Пример #13
0
  @Test
  public void testBeforeAddInterceptor() throws Exception {
    final TestClassLoader loader = getTestClassLoader();
    final String javassistClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject";

    loader.addTransformer(
        javassistClassName,
        new TransformCallback() {

          @Override
          public byte[] doInTransform(
              Instrumentor instrumentContext,
              ClassLoader classLoader,
              String className,
              Class<?> classBeingRedefined,
              ProtectionDomain protectionDomain,
              byte[] classfileBuffer)
              throws InstrumentException {
            try {
              logger.info("modify className:{} cl:{}", className, classLoader);

              InstrumentClass aClass =
                  instrumentContext.getInstrumentClass(
                      classLoader, javassistClassName, classfileBuffer);

              String methodName = "callA";
              aClass
                  .getDeclaredMethod(methodName)
                  .addInterceptor(
                      "com.navercorp.pinpoint.profiler.interceptor.TestBeforeInterceptor");

              return aClass.toBytecode();
            } catch (InstrumentException e) {
              e.printStackTrace();
              throw new RuntimeException(e.getMessage(), e);
            }
          }
        });

    loader.initialize();

    Class<?> testObjectClazz = loader.loadClass(javassistClassName);
    final String methodName = "callA";
    logger.info("class:{}", testObjectClazz.toString());
    final Object testObject = testObjectClazz.newInstance();
    Method callA = testObjectClazz.getMethod(methodName);
    callA.invoke(testObject);
    Interceptor interceptor = getInterceptor(loader, 0);
    assertEqualsIntField(interceptor, "call", 1);
    assertEqualsObjectField(
        interceptor, "className", "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject");
    assertEqualsObjectField(interceptor, "methodName", methodName);
    assertEqualsObjectField(interceptor, "args", null);

    assertEqualsObjectField(interceptor, "target", testObject);
  }
Пример #14
0
  @Test
  public void selfRefUsedForAdditionalPropertiesIsReadSuccessfully() throws NoSuchMethodException {

    Type additionalPropertiesType =
        selfRefsClass.getMethod("getAdditionalProperties").getGenericReturnType();
    Class<?> mapEntryClass =
        (Class<?>) ((ParameterizedType) additionalPropertiesType).getActualTypeArguments()[1];

    assertThat(mapEntryClass.getName(), is("com.example.SelfRefs"));
  }
  // If a player class overrides hashCode, hashCode should work normally.
  // If a player class *doesn't* override hashCode, we should replace calls to it
  // with a deterministic hash code function.
  @Test
  public void testHashCodeInstrumentation() throws Exception {
    final Class<?> overridesClass = l1.loadClass("instrumentertest.OverridesHashCode");
    final Method getHashCodeOverrides = overridesClass.getMethod("getHashCode");

    final Object overrides = overridesClass.newInstance();

    assertEquals(57, getHashCodeOverrides.invoke(overrides));
    assertEquals(57, getHashCodeOverrides.invoke(overrides));

    final Class<?> notOverridesClass1 = l1.loadClass("instrumentertest.DoesntOverrideHashCode");
    final Method getHashCodeNotOverrides1 = notOverridesClass1.getMethod("getHashCode");
    final Object notOverrides1a = notOverridesClass1.newInstance();
    final Object notOverrides1b = notOverridesClass1.newInstance();

    assertEquals(
        getHashCodeNotOverrides1.invoke(notOverrides1a),
        getHashCodeNotOverrides1.invoke(notOverrides1a));
    assertEquals(
        getHashCodeNotOverrides1.invoke(notOverrides1b),
        getHashCodeNotOverrides1.invoke(notOverrides1b));

    final Class<?> notOverridesClass2 = l2.loadClass("instrumentertest.DoesntOverrideHashCode");
    final Method getHashCodeNotOverrides2 = notOverridesClass2.getMethod("getHashCode");
    final Object notOverrides2a = notOverridesClass2.newInstance();
    final Object notOverrides2b = notOverridesClass2.newInstance();

    assertEquals(
        getHashCodeNotOverrides2.invoke(notOverrides2a),
        getHashCodeNotOverrides2.invoke(notOverrides2a));
    assertEquals(
        getHashCodeNotOverrides2.invoke(notOverrides2b),
        getHashCodeNotOverrides2.invoke(notOverrides2b));

    // hashCode should be deterministic across loaders (assuming it is called
    // in the same order.)
    assertEquals(
        getHashCodeNotOverrides1.invoke(notOverrides1a),
        getHashCodeNotOverrides2.invoke(notOverrides2a));
    assertEquals(
        getHashCodeNotOverrides1.invoke(notOverrides1b),
        getHashCodeNotOverrides2.invoke(notOverrides2b));
  }
  /** @see DATACMNS-393 */
  @Test
  public void selectsFindAllWithSortParameterOnRepositoryAmongUnsuitableAlternatives()
      throws Exception {

    Class<RepositoryWithInvalidPagingFallbackToSortFindAll> type =
        RepositoryWithInvalidPagingFallbackToSortFindAll.class;

    assertFindAllMethodOn(type, type.getMethod("findAll", Sort.class));
    assertSaveMethodPresent(type, false);
  }
Пример #17
0
  @Test
  @Ignore
  public void testTemplateCreationWithJava() throws Exception {
    this.shell.eval("(deftemplate Person (slot name (type String) ) (slot age (type int) ) )");

    this.shell.eval("(defrule yyy  => (printout t yy \" \" (eq 1 1) ) ) )");
    Package pkg = shell.getStatefulSession().getRuleBase().getPackage("MAIN");

    Rule rule = pkg.getRule("yyy");
    assertEquals("yyy", rule.getName());

    this.shell.eval(
        "(defrule xxx (Person (name ?name&bob) (age 30) ) (Person  (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )");

    rule = pkg.getRule("xxx");
    assertEquals("xxx", rule.getName());

    assertEquals(2, pkg.getRules().length);

    WorkingMemory wm = shell.getStatefulSession();
    Class personClass =
        ((InternalRuleBase) this.shell.getStatefulSession().getRuleBase())
            .getRootClassLoader()
            .loadClass("MAIN.Person");

    Method nameMethod = personClass.getMethod("setName", new Class[] {String.class});
    Method ageMethod = personClass.getMethod("setAge", new Class[] {int.class});

    Object bob1 = personClass.newInstance();
    nameMethod.invoke(bob1, "bob");
    ageMethod.invoke(bob1, 30);

    Object bob2 = personClass.newInstance();
    nameMethod.invoke(bob2, "bob");
    ageMethod.invoke(bob2, 35);
    // Constructor constructor = personClass.getConstructor( new Class[] {
    // String.class,String.class, int.class} );
    wm.insert(bob1);
    wm.insert(bob2);

    wm.fireAllRules();
    assertEquals("yy truexx true", new String(this.baos.toByteArray()));
  }
 @Test
 public void testMonitorEnterRemove() throws Exception {
   Method m1 = clazz.getMethod("m1", Callable.class);
   MyCallable mc = new MyCallable();
   assertEquals(0, mc.getCount());
   checkUnmutated(new Object[] {mc}, true, m1, clazz);
   assertEquals(0, mc.getCount());
   checkMutation(9, MutationType.MONITOR_REMOVE, 0, new Object[] {mc}, true, m1, clazz);
   assertEquals(1, mc.getCount());
 }
Пример #19
0
  @SuppressWarnings("unchecked")
  @Test
  public void test() throws Exception {
    assertThat(compile("input/Example.java"), is(true));

    URLClassLoader loader = new URLClassLoader(new URL[] {res("input/")});
    Class<?> exampleClass = loader.loadClass("Example");
    Object exampleObj = exampleClass.newInstance();
    assertThat(
        (List<String>)
            exampleClass
                .getMethod("transform", List.class)
                .invoke(exampleObj, Arrays.<Integer>asList(1, 2, 3)),
        is(Arrays.<String>asList("2", "4", "6")));
  }
Пример #20
0
  @Test
  public void testInterfaceWrapper() throws Exception {
    Calc calc = new CalcImpl();

    WrapperProxetta proxetta =
        WrapperProxetta.withAspects(
            new ProxyAspect(
                StatCounterAdvice.class,
                new ProxyPointcutSupport() {
                  public boolean apply(MethodInfo methodInfo) {
                    return isTopLevelMethod(methodInfo) && isPublic(methodInfo);
                  }
                }));

    //		proxetta.setDebugFolder("d:\\");

    // wrapper over INTERFACE
    // resulting object has ONE interface
    // only interface methods are wrapped
    WrapperProxettaBuilder builder = proxetta.builder(Calc.class, ".CalcImpl3");

    Class<Calc> calc2Class = builder.define();

    Calc calc2 = calc2Class.newInstance();

    builder.injectTargetIntoWrapper(calc, calc2);

    assertEquals(1, StatCounter.counter); // counter in static block !!!

    calc2.hello();

    assertEquals(2, StatCounter.counter);

    assertEquals(10, calc2.calculate(3, 7));

    assertEquals(3, StatCounter.counter);

    try {
      calc2Class.getMethod("customMethod");
      fail();
    } catch (Exception ex) {
    }
  }
Пример #21
0
  @Test
  public void testClassWrapperCastToInterface() throws Exception {
    Calc calc = new CalcImpl();

    WrapperProxetta proxetta =
        WrapperProxetta.withAspects(
            new ProxyAspect(
                StatCounterAdvice.class,
                new ProxyPointcutSupport() {
                  public boolean apply(MethodInfo methodInfo) {
                    return !isRootMethod(methodInfo) && isPublic(methodInfo);
                  }
                }));

    //		proxetta.setDebugFolder("d:\\");

    // wrapper over CLASS casted to interface,
    // resulting object has ONE interface
    // ALL target methods are wrapped
    WrapperProxettaBuilder builder = proxetta.builder(calc.getClass(), Calc.class, ".CalcImpl2");

    Class<Calc> calc2Class = builder.define();

    Calc calc2 = calc2Class.newInstance();

    builder.injectTargetIntoWrapper(calc, calc2);

    assertEquals(1, StatCounter.counter); // counter in static block !!!

    calc2.hello();

    assertEquals(2, StatCounter.counter);

    assertEquals(10, calc2.calculate(3, 7));

    assertEquals(3, StatCounter.counter);

    assertNotNull(calc2Class.getMethod("customMethod"));
  }
Пример #22
0
  @Test
  public void addTraceValue() throws Exception {
    final TestClassLoader loader = getTestClassLoader();
    final String javassistClassName = "com.navercorp.pinpoint.profiler.interceptor.bci.TestObject";

    loader.addTransformer(
        javassistClassName,
        new TransformCallback() {

          @Override
          public byte[] doInTransform(
              Instrumentor instrumentContext,
              ClassLoader loader,
              String className,
              Class<?> classBeingRedefined,
              ProtectionDomain protectionDomain,
              byte[] classfileBuffer)
              throws InstrumentException {
            try {
              logger.info("modify cl:{}", loader);

              InstrumentClass aClass =
                  instrumentContext.getInstrumentClass(loader, javassistClassName, classfileBuffer);

              aClass.addField(ObjectTraceValue.class.getName());
              aClass.addField(IntTraceValue.class.getName());
              aClass.addField(DatabaseInfoTraceValue.class.getName());
              aClass.addField(BindValueTraceValue.class.getName());

              String methodName = "callA";
              aClass
                  .getDeclaredMethod(methodName)
                  .addInterceptor(
                      "com.navercorp.pinpoint.profiler.interceptor.TestBeforeInterceptor");
              return aClass.toBytecode();
            } catch (InstrumentException e) {
              e.printStackTrace();
              throw new RuntimeException(e.getMessage(), e);
            }
          }
        });

    loader.initialize();

    Class<?> testObjectClazz = loader.loadClass(javassistClassName);
    final String methodName = "callA";
    logger.info("class:{}", testObjectClazz.toString());
    final Object testObject = testObjectClazz.newInstance();
    Method callA = testObjectClazz.getMethod(methodName);
    callA.invoke(testObject);

    Class<?> objectTraceValue = loader.loadClass(ObjectTraceValue.class.getName());
    Assert.assertTrue("ObjectTraceValue implements fail", objectTraceValue.isInstance(testObject));
    objectTraceValue.getMethod("_$PINPOINT$_setTraceObject", Object.class).invoke(testObject, "a");
    Object get = objectTraceValue.getMethod("_$PINPOINT$_getTraceObject").invoke(testObject);
    Assert.assertEquals("a", get);

    Class<?> intTraceValue = loader.loadClass(IntTraceValue.class.getName());
    Assert.assertTrue("IntTraceValue implements fail", intTraceValue.isInstance(testObject));
    intTraceValue.getMethod("_$PINPOINT$_setTraceInt", int.class).invoke(testObject, 1);
    int a = (Integer) intTraceValue.getMethod("_$PINPOINT$_getTraceInt").invoke(testObject);
    Assert.assertEquals(1, a);

    Class<?> databaseTraceValue = loader.loadClass(DatabaseInfoTraceValue.class.getName());
    Assert.assertTrue(
        "DatabaseInfoTraceValue implements fail", databaseTraceValue.isInstance(testObject));
    databaseTraceValue
        .getMethod("_$PINPOINT$_setTraceDatabaseInfo", DatabaseInfo.class)
        .invoke(testObject, UnKnownDatabaseInfo.INSTANCE);
    Object databaseInfo =
        databaseTraceValue.getMethod("_$PINPOINT$_getTraceDatabaseInfo").invoke(testObject);
    Assert.assertSame(UnKnownDatabaseInfo.INSTANCE, databaseInfo);
  }
  @Test
  public void testStringFormat() throws Exception {
    final Class<?> c = l1.loadClass("instrumentertest.StringFormat");

    c.getMethod("run").invoke(null);
  }
  @Test
  public void testZombieSpawnSchedule() throws Exception {
    final Class<?> c = l1.loadClass("instrumentertest.UsesSpawnSchedule");

    c.getMethod("run").invoke(null);
  }
  @Test
  public void testLambdas() throws Exception {
    final Class<?> c = l1.loadClass("instrumentertest.UsesLambda");

    c.getMethod("run").invoke(null);
  }