com.alibaba.jvm.sandbox.api.listener.EventListener Java Examples

The following examples show how to use com.alibaba.jvm.sandbox.api.listener.EventListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LogExceptionModule.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void loadCompleted() {
    new EventWatchBuilder(moduleEventWatcher)
            .onClass(Exception.class)
            .includeBootstrap()
            .onBehavior("<init>")
            .onWatch(new EventListener() {
                @Override
                public void onEvent(Event event) throws Throwable {
                    final BeforeEvent bEvent = (BeforeEvent) event;
                    exLogger.info("{} occur an exception: {}",
                            getJavaClassName(bEvent.target.getClass()),
                            bEvent.target
                    );
                }
            }, BEFORE);
}
 
Example #2
Source File: TestIssues130.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void cal$sum_add$call_before() throws Throwable {
    final Class<?> calculatorClass = JvmHelper
            .createJvm()
            .defineClass(
                    Calculator.class,
                    CALCULATOR_SUM_and_ADD_FILTER,
                    new EventListener() {

                        @Override
                        public void onEvent(Event event) throws Throwable {

                        }
                    },
                    CALL_BEFORE
            )
            .loadClass(CALCULATOR_CLASS_NAME);

    final Object objectOfCal = newInstance(calculatorClass);
    for (int i = 0; i < 1000000; i++) {
        assertEquals(30, sum(objectOfCal, 10, 20));
    }
}
 
Example #3
Source File: TestIssues130.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void cal$sum_add$line() throws Throwable {
    final Class<?> calculatorClass = JvmHelper
            .createJvm()
            .defineClass(
                    Calculator.class,
                    CALCULATOR_SUM_and_ADD_FILTER,
                    new EventListener() {

                        @Override
                        public void onEvent(Event event) throws Throwable {

                        }
                    },
                    LINE
            )
            .loadClass(CALCULATOR_CLASS_NAME);

    final Object objectOfCal = newInstance(calculatorClass);
    for (int i = 0; i < 1000000; i++) {
        assertEquals(30, sum(objectOfCal, 10, 20));
    }
}
 
Example #4
Source File: TestIssues130.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void cal$sum_add$all() throws Throwable {
    final Class<?> calculatorClass = JvmHelper
            .createJvm()
            .defineClass(
                    Calculator.class,
                    CALCULATOR_SUM_and_ADD_FILTER,
                    new EventListener() {

                        @Override
                        public void onEvent(Event event) throws Throwable {

                        }
                    },
                    Event.Type.values()
            )
            .loadClass(CALCULATOR_CLASS_NAME);

    final Object objectOfCal = newInstance(calculatorClass);
    for (int i = 0; i < 1000000; i++) {
        assertEquals(30, sum(objectOfCal, 10, 20));
    }
}
 
Example #5
Source File: TestIssues217.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void matching__TestA_or_TestB__Annotation() {

    final GetMatcherModuleEventWatcher watcher = new GetMatcherModuleEventWatcher();

    new EventWatchBuilder(watcher, REGEX)
            .onAnyClass()
            .hasAnnotationTypes(".*Test(A|B)Annotation")
            .onAnyBehavior()
            .onWatch(new EventListener() {
                @Override
                public void onEvent(Event event) throws Throwable {

                }
            });

    final Matcher matcher = watcher.getMatcher();
    Assert.assertTrue(matcher.matching(createClassStructure(TestA.class)).isMatched());
    Assert.assertTrue(matcher.matching(createClassStructure(TestB.class)).isMatched());
    Assert.assertTrue(matcher.matching(createClassStructure(TestAB.class)).isMatched());

}
 
Example #6
Source File: SandboxClassFileTransformer.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
SandboxClassFileTransformer(final int watchId,
                            final String uniqueId,
                            final Matcher matcher,
                            final EventListener eventListener,
                            final boolean isEnableUnsafe,
                            final Event.Type[] eventTypeArray,
                            final String namespace) {
    this.watchId = watchId;
    this.uniqueId = uniqueId;
    this.matcher = matcher;
    this.eventListener = eventListener;
    this.isEnableUnsafe = isEnableUnsafe;
    this.eventTypeArray = eventTypeArray;
    this.namespace = namespace;
    this.listenerId = ObjectIDs.instance.identity(eventListener);
}
 
Example #7
Source File: DefaultModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int watch(final Filter filter,
                 final EventListener listener,
                 final Progress progress,
                 final Event.Type... eventType) {
    return watch(new ExtFilterMatcher(make(filter)), listener, progress, eventType);
}
 
Example #8
Source File: TestIssues217.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void matchingComputerAnnotation() throws IOException {


    final GetMatcherModuleEventWatcher watcher = new GetMatcherModuleEventWatcher();

    new EventWatchBuilder(watcher)
            .onClass("*")
            .hasAnnotationTypes("com.alibaba.jvm.sandbox.qatest.core.enhance.target.Computer")
            .onAnyBehavior()
            .onWatch(new EventListener() {
                @Override
                public void onEvent(Event event) throws Throwable {

                }
            });

    final Matcher matcher = watcher.getMatcher();
    Assert.assertTrue(matcher.matching(createClassStructure(Calculator.class)).isMatched());
    Assert.assertTrue(matcher.matching(createClassStructure(toByteArray(Calculator.class), getClass().getClassLoader())).isMatched());

    Assert.assertFalse(matcher.matching(createClassStructure(MyCalculator.class)).isMatched());
    Assert.assertFalse(matcher.matching(createClassStructure(toByteArray(MyCalculator.class), getClass().getClassLoader())).isMatched());

    Assert.assertFalse(matcher.matching(createClassStructure(TestIssues217.class)).isMatched());
    Assert.assertFalse(matcher.matching(createClassStructure(toByteArray(TestIssues217.class), getClass().getClassLoader())).isMatched());

}
 
Example #9
Source File: DefaultModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void watching(final Filter filter,
                     final EventListener listener,
                     final Progress wProgress,
                     final WatchCallback watchCb,
                     final Progress dProgress,
                     final Event.Type... eventType) throws Throwable {
    final int watchId = watch(new ExtFilterMatcher(make(filter)), listener, wProgress, eventType);
    try {
        watchCb.watchCompleted();
    } finally {
        delete(watchId, dProgress);
    }
}
 
Example #10
Source File: TestIssues217.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void matchingInheritedComputerAnnotation() throws IOException {


    final GetMatcherModuleEventWatcher watcher = new GetMatcherModuleEventWatcher();

    new EventWatchBuilder(watcher)
            .onClass("*")
            .hasAnnotationTypes("com.alibaba.jvm.sandbox.qatest.core.enhance.target.InheritedComputer")
            .onAnyBehavior()
            .onWatch(new EventListener() {
                @Override
                public void onEvent(Event event) throws Throwable {

                }
            });

    final Matcher matcher = watcher.getMatcher();
    Assert.assertTrue(matcher.matching(createClassStructure(Calculator.class)).isMatched());
    Assert.assertTrue(matcher.matching(createClassStructure(toByteArray(Calculator.class), getClass().getClassLoader())).isMatched());

    Assert.assertTrue(matcher.matching(createClassStructure(MyCalculator.class)).isMatched());
    Assert.assertTrue(matcher.matching(createClassStructure(toByteArray(MyCalculator.class), getClass().getClassLoader())).isMatched());

    Assert.assertFalse(matcher.matching(createClassStructure(TestIssues217.class)).isMatched());
    Assert.assertFalse(matcher.matching(createClassStructure(toByteArray(TestIssues217.class), getClass().getClassLoader())).isMatched());

}
 
Example #11
Source File: DefaultModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int watch(final EventWatchCondition condition,
                 final EventListener listener,
                 final Progress progress,
                 final Event.Type... eventType) {
    return watch(toOrGroupMatcher(condition.getOrFilterArray()), listener, progress, eventType);
}
 
Example #12
Source File: MockForBuilderModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int watch(EventWatchCondition condition, EventListener listener, Progress progress, Event.Type... eventType) {
    eventWatchConditionRef.set(condition);
    eventListenerRef.set(listener);
    progressRef.set(progress);
    eventTypeArrayRef.set(eventType);
    return 0;
}
 
Example #13
Source File: EventProcessor.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
EventProcessor(final int listenerId,
               final EventListener listener,
               final Event.Type[] eventTypes) {

    this.listenerId = listenerId;
    this.eventTypes = eventTypes;
    this.listener = isInterruptEventHandler(listener.getClass())
            ? new InterruptedEventListenerImpl(listener)
            : listener;
}
 
Example #14
Source File: JvmHelper.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Transformer(final Filter filter,
                   final EventListener listener,
                   final Event.Type... eventTypes) {
    this.filter = filter;
    this.listener = listener;
    this.eventTypes = eventTypes;
}
 
Example #15
Source File: EventListenerHandler.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 注册事件处理器
 *
 * @param listenerId 事件监听器ID
 * @param listener   事件监听器
 * @param eventTypes 监听事件集合
 */
public void active(final int listenerId,
                   final EventListener listener,
                   final Event.Type[] eventTypes) {
    mappingOfEventProcessor.put(listenerId, new EventProcessor(listenerId, listener, eventTypes));
    logger.info("activated listener[id={};target={};] event={}",
            listenerId,
            listener,
            join(eventTypes, ",")
    );
}
 
Example #16
Source File: JvmHelper.java    From jvm-sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
public JvmHelper defineClass(final Class<?>[] classes,
                             final Filter filter,
                             final EventListener listener,
                             final Event.Type... eventTypes) throws IllegalAccessException, IOException, InvocationTargetException {
    return defineClass(
            classes,
            new Transformer(filter, listener, eventTypes)
    );
}
 
Example #17
Source File: JvmHelper.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ThirdTransformer(Filter filter, EventListener listener) {
    super(filter, listener, null);
}
 
Example #18
Source File: EmptyModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int watch(Filter filter, EventListener listener, Event.Type... eventType) {
    return 0;
}
 
Example #19
Source File: JvmHelper.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
public JvmHelper defineClass(final Class<?> clazz,
                             final Filter filter,
                             final EventListener listener,
                             final Event.Type... eventType) throws IllegalAccessException, IOException, InvocationTargetException {
    return defineClass(new Class<?>[]{clazz}, filter, listener, eventType);
}
 
Example #20
Source File: TestIssues217.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int watch(EventWatchCondition condition, EventListener listener, Progress progress, Event.Type... eventType) {
    this.condition = condition;
    return super.watch(condition, listener, progress, eventType);
}
 
Example #21
Source File: DebugRalphModule.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Command("wreck")
public void exception(final Map<String, String> param, final PrintWriter writer) {

    final Printer printer = new ConcurrentLinkedQueuePrinter(writer);

    // --- 解析参数 ---

    final String cnPattern = getParameter(param, "class");
    final String mnPattern = getParameter(param, "method");
    final ExceptionType exType = getParameter(
            param,
            "type",
            new Converter<ExceptionType>() {
                @Override
                public ExceptionType convert(String string) {
                    return EnumUtils.getEnum(ExceptionType.class, string);
                }
            },
            ExceptionType.RuntimeException
    );

    // --- 开始增强 ---

    final EventWatcher watcher = new EventWatchBuilder(moduleEventWatcher)
            .onClass(cnPattern)
            .includeSubClasses()
            .includeBootstrap()
            .onBehavior(mnPattern)
            .onWatching()
            .withProgress(new ProgressPrinter(printer))
            .onWatch(new EventListener() {
                @Override
                public void onEvent(Event event) throws Throwable {

                    final BeforeEvent bEvent = (BeforeEvent) event;
                    printer.println(String.format(
                            "%s.%s will be wreck by exception: %s on %s",
                            bEvent.javaClassName,
                            bEvent.javaMethodName,
                            exType.name(),
                            Thread.currentThread().getName()
                    ));

                    throwsImmediately(exType.throwIt("wreck-it by Ralph!!!"));
                }
            }, BEFORE);

    // --- 等待结束 ---

    try {
        printer.println(String.format(
                "exception on [%s#%s] exception: %s.\nPress CTRL_C abort it!",
                cnPattern,
                mnPattern,
                exType.name()
        ));
        printer.waitingForBroken();
    } finally {
        watcher.onUnWatched();
    }

}
 
Example #22
Source File: DebugRalphModule.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Command("delay")
public void delay(final Map<String, String> param, final PrintWriter writer) {

    final ReentrantLock delayLock = new ReentrantLock();
    final Condition delayCondition = delayLock.newCondition();
    final Printer printer = new ConcurrentLinkedQueuePrinter(writer);
    final AtomicBoolean isFinishRef = new AtomicBoolean(false);

    // --- 解析参数 ---

    final String cnPattern = getParameter(param, "class");
    final String mnPattern = getParameter(param, "method");
    final long delayMs = getParameter(param, "delay", long.class);

    // --- 开始增强 ---

    final EventWatcher watcher = new EventWatchBuilder(moduleEventWatcher)
            .onClass(cnPattern)
            .includeSubClasses()
            .includeBootstrap()
            .onBehavior(mnPattern)
            .onWatching()
            .withProgress(new ProgressPrinter(printer))
            .onWatch(new EventListener() {
                @Override
                public void onEvent(Event event) throws Throwable {

                    final BeforeEvent bEvent = (BeforeEvent) event;
                    printer.println(String.format(
                            "%s.%s will be delay %s(ms) on %s",
                            bEvent.javaClassName,
                            bEvent.javaMethodName,
                            delayMs,
                            Thread.currentThread().getName()
                    ));

                    delayLock.lock();
                    try {
                        // 如果已经结束,则放弃本次请求
                        if (isFinishRef.get()) {
                            return;
                        }
                        delayCondition.await(delayMs, TimeUnit.MILLISECONDS);
                    } finally {
                        delayLock.unlock();
                    }
                }
            }, BEFORE);

    // --- 等待结束 ---

    try {
        printer.println(String.format(
                "delay on [%s#%s] %s(ms).\nPress CTRL_C abort it!",
                cnPattern,
                mnPattern,
                delayMs
        ));
        printer.waitingForBroken();
    } finally {

        // 释放锁
        delayLock.lock();
        try {
            isFinishRef.set(true);
            delayCondition.signalAll();
        } finally {
            delayLock.unlock();
        }

        watcher.onUnWatched();
    }
}
 
Example #23
Source File: TestIssues253.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void cal$sum_add$with_EventListener$add_throwsImmediately_sum_catchException() throws Throwable {

    final Class<?> calculatorClass = JvmHelper
            .createJvm()
            .defineClass(
                    Calculator.class,
                    CALCULATOR_SUM_and_ADD_FILTER,
                    new EventListener() {

                        private final Stack<String> stack = new Stack<String>();
                        int count = 0;

                        @Override
                        public void onEvent(Event event) throws Throwable {
                            final InvokeEvent iEvent = (InvokeEvent)event;
                            switch (event.type) {
                                case BEFORE: {
                                    stack.push(((BeforeEvent) event).javaMethodName);
                                    break;
                                }
                                case RETURN: {
                                    if (stack.pop().equals("add")) {
                                        ProcessController.throwsImmediately(new RuntimeException("test:"+(++count)));
                                    }
                                    break;
                                }
                                case THROWS: {
                                    if (stack.pop().equals("sum")) {
                                        ProcessController.returnImmediately(100);
                                    }
                                    break;
                                }
                            }

                        }
                    },
                    BEFORE, RETURN, THROWS
            )
            .loadClass(CALCULATOR_CLASS_NAME);

    final Object objectOfCal = newInstance(calculatorClass);
    assertEquals(100, sum(objectOfCal, 10, 20));
}
 
Example #24
Source File: TestIssues109.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void cal$sum_add$all$multi_thread() throws Throwable {
    final ThreadLocal<List<Event.Type>> tracingRef = new ThreadLocal<List<Event.Type>>() {
        @Override
        protected List<Event.Type> initialValue() {
            return new ArrayList<Event.Type>();
        }
    };
    final Class<?> calculatorClass = JvmHelper
            .createJvm()
            .defineClass(
                    Calculator.class,
                    CALCULATOR_SUM_and_ADD_FILTER,
                    new EventListener() {

                        @Override
                        public void onEvent(Event event) {
                            tracingRef.get().add(event.type);
                        }

                    },
                    Event.Type.values()
            )
            .loadClass(CALCULATOR_CLASS_NAME);

    final Object objectOfCal = newInstance(calculatorClass);

    final int total = 10000;
    final int concurrent = 700;
    final AtomicInteger successCntRef = new AtomicInteger();
    final CountDownLatch countDownLatch = new CountDownLatch(total);
    final ExecutorService executors = Executors.newFixedThreadPool(concurrent);
    try {
        for (int index = 0; index < total; index++) {
            executors.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        assertEquals(30, sum(objectOfCal, 10, 20));
                        assertArrayEquals(
                                ArrayUtils.toArray(BEFORE, LINE, LINE, LINE, LINE, CALL_BEFORE, BEFORE, LINE, LINE, RETURN, CALL_RETURN, LINE, LINE, CALL_BEFORE, BEFORE, LINE, LINE, RETURN, CALL_RETURN, LINE, LINE, RETURN),
                                tracingRef.get().toArray(new Event.Type[]{})
                        );
                        successCntRef.getAndIncrement();
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                    } finally {
                        tracingRef.remove();
                        countDownLatch.countDown();
                    }
                }
            });
        }
        countDownLatch.await();
        Assert.assertEquals(total, successCntRef.get());
    } finally {
        executors.shutdown();
    }

}
 
Example #25
Source File: MockForBuilderModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
public EventListener getEventListener() {
    return eventListenerRef.get();
}
 
Example #26
Source File: MockForBuilderModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int watch(Filter filter, EventListener listener, Progress progress, Event.Type... eventType) {
    return 0;
}
 
Example #27
Source File: EmptyModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int watch(EventWatchCondition condition, EventListener listener, Progress progress, Event.Type... eventType) {
    return 0;
}
 
Example #28
Source File: EmptyModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int watch(Filter filter, EventListener listener, Progress progress, Event.Type... eventType) {
    return 0;
}
 
Example #29
Source File: TracingAdviceListener.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
TracingAdviceListener setEventListener(EventListener eventListener) {
    this.eventListener = eventListener;
    return this;
}
 
Example #30
Source File: MockForBuilderModuleEventWatcher.java    From jvm-sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int watch(Filter filter, EventListener listener, Event.Type... eventType) {
    return 0;
}