1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
|
/*
* Copyright (C) 2008 Google Inc.
*
* 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.
*/
package com.google.inject;
import static com.google.common.truth.Truth.assertThat;
import static com.google.inject.matcher.Matchers.only;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.internal.InternalFlags;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
import com.google.inject.spi.ConstructorBinding;
import com.google.inject.spi.DefaultElementVisitor;
import com.google.inject.spi.Element;
import com.google.inject.spi.InterceptorBinding;
import java.lang.annotation.Retention;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Named;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** @author jessewilson@google.com (Jesse Wilson) */
@RunWith(JUnit4.class)
public class MethodInterceptionTest {
private AtomicInteger count = new AtomicInteger();
private final class CountingInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
count.incrementAndGet();
return methodInvocation.proceed();
}
}
private static final class ReturnNullInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
return null;
}
}
private static final class NoOpInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
return methodInvocation.proceed();
}
}
@Before
public void checkBytecodeGenIsEnabled() {
assumeTrue(InternalFlags.isBytecodeGenEnabled());
}
@Test
public void testSharedProxyClasses() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(), Matchers.returns(only(Foo.class)), new ReturnNullInterceptor());
}
});
Injector childOne =
injector.createChildInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Interceptable.class);
}
});
Interceptable nullFoosOne = childOne.getInstance(Interceptable.class);
assertNotNull(nullFoosOne.bar());
assertNull(nullFoosOne.foo()); // confirm it's being intercepted
Injector childTwo =
injector.createChildInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Interceptable.class);
}
});
Interceptable nullFoosTwo = childTwo.getInstance(Interceptable.class);
assertNull(nullFoosTwo.foo()); // confirm it's being intercepted
assertSame(
"Child injectors should share proxy classes, otherwise memory leaks!",
nullFoosOne.getClass(),
nullFoosTwo.getClass());
Injector injector2 =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(), Matchers.returns(only(Foo.class)), new ReturnNullInterceptor());
}
});
Interceptable separateNullFoos = injector2.getInstance(Interceptable.class);
assertNull(separateNullFoos.foo()); // confirm it's being intercepted
assertSame(
"different injectors should share proxy classes, otherwise memory leaks!",
nullFoosOne.getClass(),
separateNullFoos.getClass());
}
@Test
public void testGetThis() {
final AtomicReference<Object> lastTarget = new AtomicReference<>();
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(),
Matchers.any(),
new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
lastTarget.set(methodInvocation.getThis());
return methodInvocation.proceed();
}
});
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
interceptable.foo();
assertSame(interceptable, lastTarget.get());
}
@Test
public void testInterceptingFinalClass() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(),
Matchers.any(),
new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
return methodInvocation.proceed();
}
});
}
});
try {
injector.getInstance(NotInterceptable.class);
fail();
} catch (ConfigurationException ce) {
assertEquals(
"Unable to method intercept: " + NotInterceptable.class.getName(),
Iterables.getOnlyElement(ce.getErrorMessages()).getMessage().toString());
assertEquals(
"Cannot subclass final class " + NotInterceptable.class.getName(),
ce.getCause().getMessage());
}
}
@Test
public void testSpiAccessToInterceptors() throws NoSuchMethodException {
final MethodInterceptor countingInterceptor = new CountingInterceptor();
final MethodInterceptor returnNullInterceptor = new ReturnNullInterceptor();
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(), Matchers.returns(only(Foo.class)), countingInterceptor);
bindInterceptor(
Matchers.any(),
Matchers.returns(only(Foo.class).or(only(Bar.class))),
returnNullInterceptor);
}
});
ConstructorBinding<?> interceptedBinding =
(ConstructorBinding<?>) injector.getBinding(Interceptable.class);
Method barMethod = Interceptable.class.getMethod("bar");
Method fooMethod = Interceptable.class.getMethod("foo");
assertEquals(
ImmutableMap.<Method, List<MethodInterceptor>>of(
fooMethod, ImmutableList.of(countingInterceptor, returnNullInterceptor),
barMethod, ImmutableList.of(returnNullInterceptor)),
interceptedBinding.getMethodInterceptors());
ConstructorBinding<?> nonInterceptedBinding =
(ConstructorBinding<?>) injector.getBinding(Foo.class);
assertEquals(
ImmutableMap.<Method, List<MethodInterceptor>>of(),
nonInterceptedBinding.getMethodInterceptors());
injector.getInstance(Interceptable.class).foo();
assertEquals("expected counting interceptor to be invoked first", 1, count.get());
}
@Test
public void testGetElements_interceptorBindings() throws Exception {
@SuppressWarnings("rawtypes")
Matcher<Class> classMatcher = Matchers.subclassesOf(List.class);
Matcher<Method> methodMatcher = Matchers.returns(Matchers.identicalTo(int.class));
MethodInterceptor interceptor =
new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
return null;
}
};
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(classMatcher, methodMatcher, interceptor);
}
});
final List<InterceptorBinding> interceptorBindings = new ArrayList<>();
for (Element element : injector.getElements()) {
element.acceptVisitor(
new DefaultElementVisitor<Void>() {
@Override
public Void visit(InterceptorBinding interceptorBinding) {
interceptorBindings.add(interceptorBinding);
return null;
}
});
}
assertThat(interceptorBindings).hasSize(1);
InterceptorBinding extractedBinding = interceptorBindings.get(0);
assertSame(classMatcher, extractedBinding.getClassMatcher());
assertSame(methodMatcher, extractedBinding.getMethodMatcher());
assertSame(interceptor, extractedBinding.getInterceptors().get(0));
}
@Test
public void testInterceptedMethodThrows() throws Exception {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.any(), new CountingInterceptor());
bindInterceptor(Matchers.any(), Matchers.any(), new CountingInterceptor());
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
try {
interceptable.explode();
fail();
} catch (Exception e) {
// validate all causes.
for (Throwable t = e; t != null; t = t.getCause()) {
StackTraceElement[] stackTraceElement = t.getStackTrace();
int frame = 0;
assertEquals("explode", stackTraceElement[frame++].getMethodName());
while (stackTraceElement[frame].getClassName().startsWith("java.lang.invoke.LambdaForm")) {
frame++; // ignore lambda frames when running tests with ShowHiddenFrames
}
assertEquals("invoke", stackTraceElement[frame++].getMethodName());
assertEquals("invoke", stackTraceElement[frame++].getMethodName());
assertEquals("testInterceptedMethodThrows", stackTraceElement[frame++].getMethodName());
}
}
}
@Test
public void testNotInterceptedMethodsInInterceptedClassDontAddFrames() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(), Matchers.returns(only(Foo.class)), new NoOpInterceptor());
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
assertNull(interceptable.lastElements);
interceptable.foo();
boolean proxyFrameFound = false;
for (int i = 0; i < interceptable.lastElements.length; i++) {
if (interceptable.lastElements[i].toString().contains("$EnhancerByGuice$")) {
proxyFrameFound = true;
break;
}
}
assertTrue(Arrays.toString(interceptable.lastElements), proxyFrameFound);
proxyFrameFound = false;
interceptable.bar();
for (int i = 0; i < interceptable.lastElements.length; i++) {
if (interceptable.lastElements[i].toString().contains("$EnhancerByGuice$")) {
proxyFrameFound = true;
break;
}
}
assertFalse(Arrays.toString(interceptable.lastElements), proxyFrameFound);
}
public static class Foo {}
static class Bar {}
public static class Interceptable {
StackTraceElement[] lastElements;
public Foo foo() {
lastElements = Thread.currentThread().getStackTrace();
return new Foo() {};
}
public Bar bar() {
lastElements = Thread.currentThread().getStackTrace();
return new Bar() {};
}
public String explode() throws Exception {
lastElements = Thread.currentThread().getStackTrace();
throw new Exception("kaboom!", new RuntimeException("boom!"));
}
}
public static final class NotInterceptable {}
@Test
public void testInterceptingNonBridgeWorks() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Interface.class).to(Impl.class);
bindInterceptor(
Matchers.any(),
new AbstractMatcher<Method>() {
@Override
public boolean matches(Method t) {
return !t.isBridge() && t.getDeclaringClass() != Object.class;
}
},
new CountingInterceptor());
}
});
Interface intf = injector.getInstance(Interface.class);
assertEquals(0, count.get());
intf.aMethod(null);
assertEquals(1, count.get());
}
static class ErasedType {}
static class RetType extends ErasedType {}
abstract static class Superclass<T extends ErasedType> {
public T aMethod(T t) {
return null;
}
}
public interface Interface {
RetType aMethod(RetType obj);
}
public static class Impl extends Superclass<RetType> implements Interface {}
@Test
public void testInterceptionOrder() {
final List<String> callList = Lists.newArrayList();
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(),
Matchers.any(),
new NamedInterceptor("a", callList),
new NamedInterceptor("b", callList),
new NamedInterceptor("c", callList));
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
assertEquals(0, callList.size());
interceptable.foo();
assertEquals(Arrays.asList("a", "b", "c"), callList);
}
private static final class NamedInterceptor implements MethodInterceptor {
private final String name;
final List<String> called;
NamedInterceptor(String name, List<String> callList) {
this.name = name;
this.called = callList;
}
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
called.add(name);
return methodInvocation.proceed();
}
}
@Test
public void testDeDuplicateInterceptors() throws Exception {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
CountingInterceptor interceptor = new CountingInterceptor();
bindInterceptor(Matchers.any(), Matchers.any(), interceptor);
bindInterceptor(Matchers.any(), Matchers.any(), interceptor);
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
interceptable.foo();
assertEquals(1, count.get());
}
@Test
public void testCallLater() {
final Queue<Runnable> queue = Lists.newLinkedList();
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.any(), new CallLaterInterceptor(queue));
}
});
Interceptable interceptable = injector.getInstance(Interceptable.class);
interceptable.foo();
assertNull(interceptable.lastElements);
assertEquals(1, queue.size());
queue.remove().run();
assertNotNull(interceptable.lastElements);
}
private static final class CallLaterInterceptor implements MethodInterceptor {
private final Queue<Runnable> queue;
public CallLaterInterceptor(Queue<Runnable> queue) {
this.queue = queue;
}
@Override
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
queue.add(
() -> {
try {
methodInvocation.proceed();
} catch (Throwable t) {
throw new RuntimeException(t);
}
});
return null;
}
}
@Retention(RUNTIME)
@interface Grounded {}
interface Animal {
default String identifyMyself() {
return "I am an animal.";
}
}
interface Horse extends Animal {
@Override
@Grounded
default String identifyMyself() {
return "I am a horse.";
}
}
interface MythicalAnimal extends Animal {}
interface FlyingHorse extends Horse, MythicalAnimal {
@Override
// not Grounded
default String identifyMyself() {
return "I am a flying horse.";
}
}
static class HorseImpl implements Horse {}
// MythicalAnimal shouldn't disturb earlier hierarchy
public static class Unicorn extends HorseImpl implements MythicalAnimal {}
// FlyingHorse should be merged into earlier hierarchy
public static class Pegasus extends HorseImpl implements MythicalAnimal, FlyingHorse {}
@Test
public void testDefaultMethodInterception() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(Grounded.class),
new CountingInterceptor());
}
});
assertEquals(0, count.get());
assertEquals("I am a horse.", injector.getInstance(Unicorn.class).identifyMyself());
assertEquals(1, count.get()); // unicorn is grounded
count.set(0); // reset
assertEquals(0, count.get());
assertEquals("I am a flying horse.", injector.getInstance(Pegasus.class).identifyMyself());
assertEquals(0, count.get()); // pegasus is not grounded
}
static class BaseSetter {
String text;
@Inject
protected void setText(@Named("text") String text) {
this.text = text;
}
}
public static class Setter extends BaseSetter {}
@Test
public void testSetterInterception() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("text")).to("Hello, world");
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(Inject.class),
mi -> {
mi.getArguments()[0] = ">>" + mi.getArguments()[0] + "<<";
return mi.proceed();
});
}
});
Setter setter = injector.getInstance(Setter.class);
assertEquals(">>Hello, world<<", setter.text);
}
@Retention(RUNTIME)
@interface Intercept {}
interface RawReturn {
String testReturn();
}
abstract static class GenericReturn<R> {
@Intercept
public R testReturn() {
return null;
}
}
public static class MixedReturn extends GenericReturn<String> implements RawReturn {}
@Test
public void testInterceptionWithMixedReturnTypes() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(RawReturn.class).to(MixedReturn.class);
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(Intercept.class),
mi -> {
Object result = mi.proceed();
return result != null ? result : "NULL_RETURN";
});
}
});
RawReturn ret = injector.getInstance(RawReturn.class);
assertEquals("NULL_RETURN", ret.testReturn());
}
interface ShardedStringProvider extends Provider<String> {
String get(int shard);
}
public static class ShardedStringProviderImpl implements ShardedStringProvider {
@Override
public String get() {
return get(3);
}
@Override
@Intercept
public String get(int i) {
return "" + i;
}
}
@Test
public void testProviderInterception() {
Injector injector =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(ShardedStringProvider.class).to(ShardedStringProviderImpl.class);
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(Intercept.class),
mi -> ">>" + mi.proceed() + "<<");
}
});
ShardedStringProvider provider = injector.getInstance(ShardedStringProvider.class);
assertEquals(">>3<<", provider.get());
assertEquals(">>8<<", provider.get(8));
}
@Test
public void testInterceptionWithSimilarlyNamedMethodThatAffectsOrdering() {
CountingInterceptor interceptor = new CountingInterceptor();
BarGetter getter =
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bindInterceptor(Matchers.any(), new InterceptChecker(), interceptor);
}
})
.getInstance(BarGetter.class);
assertThat(count.get()).isEqualTo(0);
getter.get();
assertThat(count.get()).isEqualTo(1);
}
private static class InterceptChecker extends AbstractMatcher<Method> {
@Override
public boolean matches(Method m) {
return !m.isSynthetic() && !m.isBridge() && m.isAnnotationPresent(Intercept.class);
}
}
public static class BarGetter implements Provider<Bar> {
@Override
@Intercept
public Bar get() {
return null;
}
public Bar get(Foo foo) {
return null;
}
}
}
|