Search in sources :

Example 1 with ClassDefinition

use of java.lang.instrument.ClassDefinition in project byte-buddy by raphw.

the class AgentBuilderRedefinitionStrategyResubmissionStrategyTest method testRedefinition.

@Test
@SuppressWarnings("unchecked")
public void testRedefinition() throws Exception {
    when(instrumentation.isModifiableClass(Foo.class)).thenReturn(true);
    when(redefinitionBatchAllocator.batch(Mockito.any(List.class))).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return Collections.singleton(invocationOnMock.getArgumentAt(0, List.class));
        }
    });
    when(rawMatcher.matches(new TypeDescription.ForLoadedType(Foo.class), Foo.class.getClassLoader(), JavaModule.ofType(Foo.class), Foo.class, Foo.class.getProtectionDomain())).thenReturn(true);
    when(matcher.matches(error)).thenReturn(true);
    when(resubmissionScheduler.isAlive()).thenReturn(true);
    ClassFileLocator classFileLocator = mock(ClassFileLocator.class);
    when(locationStrategy.classFileLocator(Foo.class.getClassLoader(), JavaModule.ofType(Foo.class))).thenReturn(classFileLocator);
    when(classFileLocator.locate(Foo.class.getName())).thenReturn(new ClassFileLocator.Resolution.Explicit(new byte[] { 1, 2, 3 }));
    AgentBuilder.RedefinitionStrategy.ResubmissionStrategy.Installation installation = new AgentBuilder.RedefinitionStrategy.ResubmissionStrategy.Enabled(resubmissionScheduler, matcher).install(instrumentation, locationStrategy, listener, installationListener, circularityLock, rawMatcher, AgentBuilder.RedefinitionStrategy.REDEFINITION, redefinitionBatchAllocator, redefinitionListener);
    installation.getInstallationListener().onInstall(instrumentation, classFileTransformer);
    installation.getListener().onError(Foo.class.getName(), Foo.class.getClassLoader(), JavaModule.ofType(Foo.class), false, error);
    ArgumentCaptor<Runnable> argumentCaptor = ArgumentCaptor.forClass(Runnable.class);
    verify(resubmissionScheduler).isAlive();
    verify(resubmissionScheduler).schedule(argumentCaptor.capture());
    argumentCaptor.getValue().run();
    verifyNoMoreInteractions(resubmissionScheduler);
    verify(instrumentation).isModifiableClass(Foo.class);
    verify(instrumentation).redefineClasses(Mockito.argThat(new BaseMatcher<ClassDefinition[]>() {

        @Override
        public boolean matches(Object o) {
            return ((ClassDefinition) o).getDefinitionClass() == Foo.class && Arrays.equals(((ClassDefinition) o).getDefinitionClassFile(), new byte[] { 1, 2, 3 });
        }

        @Override
        public void describeTo(Description description) {
        }
    }));
    verifyNoMoreInteractions(instrumentation);
    verify(rawMatcher).matches(new TypeDescription.ForLoadedType(Foo.class), Foo.class.getClassLoader(), JavaModule.ofType(Foo.class), Foo.class, Foo.class.getProtectionDomain());
    verifyNoMoreInteractions(rawMatcher);
    verify(redefinitionBatchAllocator).batch(Collections.<Class<?>>singletonList(Foo.class));
    verifyNoMoreInteractions(redefinitionBatchAllocator);
    verify(listener).onError(Foo.class.getName(), Foo.class.getClassLoader(), JavaModule.ofType(Foo.class), false, error);
    verifyNoMoreInteractions(listener);
    verify(matcher).matches(error);
    verifyNoMoreInteractions(matcher);
}
Also used : Description(org.hamcrest.Description) TypeDescription(net.bytebuddy.description.type.TypeDescription) ClassDefinition(java.lang.instrument.ClassDefinition) ClassFileLocator(net.bytebuddy.dynamic.ClassFileLocator) BaseMatcher(org.hamcrest.BaseMatcher) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TypeDescription(net.bytebuddy.description.type.TypeDescription) List(java.util.List) Test(org.junit.Test)

Example 2 with ClassDefinition

use of java.lang.instrument.ClassDefinition in project byte-buddy by raphw.

the class ClassReloadingStrategyTest method testPreregisteredType.

@Test
public void testPreregisteredType() throws Exception {
    Instrumentation instrumentation = mock(Instrumentation.class);
    ClassLoader classLoader = mock(ClassLoader.class);
    when(instrumentation.isRedefineClassesSupported()).thenReturn(true);
    when(instrumentation.getInitiatedClasses(classLoader)).thenReturn(new Class<?>[0]);
    ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.of(instrumentation).preregistered(Object.class);
    ArgumentCaptor<ClassDefinition> classDefinition = ArgumentCaptor.forClass(ClassDefinition.class);
    classReloadingStrategy.load(classLoader, Collections.singletonMap(TypeDescription.OBJECT, new byte[] { 1, 2, 3 }));
    verify(instrumentation).redefineClasses(classDefinition.capture());
    assertEquals(Object.class, classDefinition.getValue().getDefinitionClass());
    assertThat(classDefinition.getValue().getDefinitionClassFile(), is(new byte[] { 1, 2, 3 }));
}
Also used : Instrumentation(java.lang.instrument.Instrumentation) ClassDefinition(java.lang.instrument.ClassDefinition) Test(org.junit.Test)

Example 3 with ClassDefinition

use of java.lang.instrument.ClassDefinition in project jdk8u_jdk by JetBrains.

the class RedefineMethodInBacktraceApp method doRedefine.

private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f.getAbsolutePath());
    InputStream redefineStream = new FileInputStream(f);
    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);
    ClassDefinition redefineParamBlock = new ClassDefinition(clazz, redefineBuffer);
    RedefineMethodInBacktraceAgent.getInstrumentation().redefineClasses(new ClassDefinition[] { redefineParamBlock });
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ClassDefinition(java.lang.instrument.ClassDefinition) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 4 with ClassDefinition

use of java.lang.instrument.ClassDefinition in project jdk8u_jdk by JetBrains.

the class NullRedefineClassesTests method testNullRedefineClasses.

public void testNullRedefineClasses() throws ClassNotFoundException, UnmodifiableClassException {
    boolean caught;
    // Test that a null argument throws NullPointerException
    caught = false;
    try {
        fInst.redefineClasses(null);
    } catch (NullPointerException npe) {
        caught = true;
    }
    assertTrue(caught);
    // Test that a null element throws NullPointerException
    caught = false;
    try {
        fInst.redefineClasses(new ClassDefinition[] { null });
    } catch (NullPointerException npe) {
        caught = true;
    }
    assertTrue(caught);
    // Test that a null element amonst others throws NullPointerException
    caught = false;
    ClassDefinition cd = new ClassDefinition(DummyClass.class, new byte[] { 1, 2, 3 });
    try {
        fInst.redefineClasses(new ClassDefinition[] { cd, null });
    } catch (NullPointerException npe) {
        caught = true;
    }
    assertTrue(caught);
    // Test that a null class throws NullPointerException
    caught = false;
    try {
        new ClassDefinition(null, new byte[] { 1, 2, 3 });
    } catch (NullPointerException npe) {
        caught = true;
    }
    assertTrue(caught);
    // Test that a null byte array throws NullPointerException
    caught = false;
    try {
        new ClassDefinition(DummyClass.class, null);
    } catch (NullPointerException npe) {
        caught = true;
    }
    assertTrue(caught);
}
Also used : ClassDefinition(java.lang.instrument.ClassDefinition)

Example 5 with ClassDefinition

use of java.lang.instrument.ClassDefinition in project webpieces by deanhiller.

the class CompilingClassloader method isNeedToReloadJavaFiles.

/**
     * Detect Java changes
     */
public boolean isNeedToReloadJavaFiles() {
    // Now check for file modification
    List<CompileClassMeta> modifieds = new ArrayList<CompileClassMeta>();
    for (CompileClassMeta applicationClass : appClassMgr.all()) {
        if (applicationClass.javaFile.lastModified() > applicationClass.timestamp) {
            applicationClass.refresh();
            modifieds.add(applicationClass);
        }
    }
    Set<CompileClassMeta> modifiedWithDependencies = new HashSet<CompileClassMeta>();
    modifiedWithDependencies.addAll(modifieds);
    List<ClassDefinition> newDefinitions = new ArrayList<ClassDefinition>();
    for (CompileClassMeta applicationClass : modifiedWithDependencies) {
        if (applicationClass.compile(compiler, this) == null) {
            appClassMgr.classes.remove(applicationClass.name);
            throw new IllegalStateException("In what case can this ever happen in?");
        } else {
            byteCodeCache.cacheBytecode(applicationClass.javaByteCode, applicationClass.name, applicationClass.javaSource);
            //in rare case where outerclass is outside scope of compiling, but inner static class can be recompiled
            if (applicationClass.javaClass == null) {
                loadApplicationClass(applicationClass.name);
            }
            newDefinitions.add(new ClassDefinition(applicationClass.javaClass, applicationClass.javaByteCode));
        }
    }
    if (newDefinitions.size() > 0) {
        //Cache.clear();
        if (HotswapAgent.enabled) {
            try {
                HotswapAgent.reload(newDefinitions.toArray(new ClassDefinition[newDefinitions.size()]));
            } catch (Throwable e) {
                return true;
            }
        } else {
            return true;
        }
    }
    // Now check if there is new classes or removed classes
    int hash = classStateHashCreator.computePathHash(config.getJavaPath());
    if (hash != this.pathHash) {
        // Remove class for deleted files !!
        for (CompileClassMeta applicationClass : appClassMgr.all()) {
            if (!applicationClass.javaFile.exists()) {
                appClassMgr.classes.remove(applicationClass.name);
            }
            if (applicationClass.name.contains("$")) {
                appClassMgr.classes.remove(applicationClass.name);
                // Ok we have to remove all classes from the same file ...
                VirtualFile vf = applicationClass.javaFile;
                for (CompileClassMeta ac : appClassMgr.all()) {
                    if (ac.javaFile.equals(vf)) {
                        appClassMgr.classes.remove(ac.name);
                    }
                }
            }
        }
        return true;
    }
    return false;
}
Also used : VirtualFile(org.webpieces.util.file.VirtualFile) ArrayList(java.util.ArrayList) ClassDefinition(java.lang.instrument.ClassDefinition) HashSet(java.util.HashSet)

Aggregations

ClassDefinition (java.lang.instrument.ClassDefinition)8 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 TypeDescription (net.bytebuddy.description.type.TypeDescription)2 Test (org.junit.Test)2 IOException (java.io.IOException)1 Instrumentation (java.lang.instrument.Instrumentation)1 UnmodifiableClassException (java.lang.instrument.UnmodifiableClassException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ClassFileLocator (net.bytebuddy.dynamic.ClassFileLocator)1 BaseMatcher (org.hamcrest.BaseMatcher)1 Description (org.hamcrest.Description)1 InvocationOnMock (org.mockito.invocation.InvocationOnMock)1 VirtualFile (org.webpieces.util.file.VirtualFile)1