Java Code Examples for com.google.common.reflect.Reflection#newProxy()

The following examples show how to use com.google.common.reflect.Reflection#newProxy() . 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: UniformVisitor.java    From closure-stylesheets with Apache License 2.0 6 votes vote down vote up
/** Transforms the given {@code UniformVisitor} into a {@code CssTreeVisitor}. */
public static CssTreeVisitor asVisitor(final UniformVisitor visitor) {
  return Reflection.newProxy(
      CssTreeVisitor.class,
      new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          // Allow methods from Object, like toString().
          if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(visitor, args);
          }

          CssNode node = (CssNode) args[0];
          if (method.getName().startsWith("enter")) {
            visitor.enter(node);
            return true; // Always visit children
          } else if (method.getName().startsWith("leave")) {
            visitor.leave(node);
            return null; // All leave* methods are void
          }
          throw new IllegalStateException("Unexpected method '" + method + "' called");
        }
      });
}
 
Example 2
Source File: AdWordsServicesWithRateLimiter.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Decide whether this RateLimiter extension is applicable to the original service / utility
 * object. If so, wrap it in a proxy object with rate-limit-aware invocation handle; if not, just
 * return the original object.
 */
private <T> T getProxyObject(
    T originalObject, AdWordsSession session, Class<T> cls, boolean isUtility) {
  // Find the retry strategy of this class type.
  ApiRetryStrategy retryStrategy =
      ApiRetryStrategyManager.getRetryStrategy(cls.getSimpleName(), isUtility);

  // If no corresponding retry strategy, just use the original object instead of a wrapping proxy.
  if (retryStrategy == null) {
    return originalObject;
  }

  InvocationHandler invocationHandler =
      new ApiInvocationHandlerWithRateLimiter(originalObject, session, retryStrategy);
  return Reflection.newProxy(cls, invocationHandler);
}
 
Example 3
Source File: OstrichAccessors.java    From emodb with Apache License 2.0 6 votes vote down vote up
public static <S> PartitionContextValidator<S> newPartitionContextTest(final Class<S> ifc, final Class<? extends S> impl) {
    final PartitionContextSupplier supplier = new AnnotationPartitionContextSupplier(ifc, impl);
    return new PartitionContextValidator<S>() {
        @Override
        public S expect(final PartitionContext expected) {
            return Reflection.newProxy(ifc, new AbstractInvocationHandler() {
                @Override
                protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                    PartitionContext actual = supplier.forCall(method, args);
                    assertEquals(actual, expected, "Expected=" + expected.asMap() + ", Actual=" + actual.asMap());
                    return Defaults.defaultValue(method.getReturnType());
                }
            });
        }
    };
}
 
Example 4
Source File: ServiceQuery.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new service query builder by copying all properties from the passed service
 * query builder.
 *
 * @param builderInterface the service query builder whose properties will be copied to.
 */
@SuppressWarnings("unchecked")
public Builder(BuilderInterface<Page, SortOrder> builderInterface) {
  checkNotNull(builderInterface, "The service query builder cannot be null.");
  Builder builder = (Builder) builderInterface;
  proxiedImpl = new ServiceQueryBuilderImpl(builder.proxiedImpl);
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(
          proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry());
  this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler);
}
 
Example 5
Source File: ReportQuery.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Constructs a new report query builder. */
public Builder() {
  proxiedImpl = new ReportQueryBuilderImpl(this);
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(
          proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry());
  this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler);
}
 
Example 6
Source File: GeneratedAnnotationsTest.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Run {@link TestProcessor} in a compilation with the given {@code options}, and prevent the
 * compilation from accessing classes with the qualified names in {@code maskFromClasspath}.
 */
private String runProcessor(ImmutableList<String> options, String packageToMask)
    throws IOException {
  File tempDir = temporaryFolder.newFolder();
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager standardFileManager =
      compiler.getStandardFileManager(/* diagnostics= */ null, /* locale= */ null, UTF_8);
  standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(tempDir));
  StandardJavaFileManager proxyFileManager =
      Reflection.newProxy(
          StandardJavaFileManager.class,
          new FileManagerInvocationHandler(standardFileManager, packageToMask));
  CompilationTask task =
      compiler.getTask(
          /* out= */ null,
          proxyFileManager,
          /* diagnosticListener= */ null,
          options,
          /* classes= */ null,
          ImmutableList.of(
              new SimpleJavaFileObject(URI.create("test"), Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors)
                    throws IOException {
                  return "class Test {}";
                }
              }));
  task.setProcessors(ImmutableList.of(new TestProcessor()));
  assertThat(task.call()).isTrue();
  return new String(Files.readAllBytes(tempDir.toPath().resolve("G.java")), UTF_8);
}
 
Example 7
Source File: DelegatingVisitor.java    From closure-stylesheets with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@code DelegatingVisitor} from the given list of visitors. The list must have at
 * least one element.
 */
public static CssTreeVisitor from(List<CssTreeVisitor> originalVisitors) {
  Preconditions.checkArgument(originalVisitors.size() >= 1);
  if (originalVisitors.size() == 1) {
    return originalVisitors.get(0);
  }

  final ImmutableList<CssTreeVisitor> visitors = ImmutableList.copyOf(originalVisitors);
  final ImmutableList<CssTreeVisitor> reverseVisitors = visitors.reverse();
  return Reflection.newProxy(
      CssTreeVisitor.class,
      new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          try {
            Object returnValue = null;
            Iterable<CssTreeVisitor> visitorsInOrderForMethod;
            if (method.getName().startsWith("enter")) {
              visitorsInOrderForMethod = visitors;
            } else { // assume it's a leave* method
              visitorsInOrderForMethod = reverseVisitors;
            }
            for (CssTreeVisitor visitor : visitorsInOrderForMethod) {
              returnValue = method.invoke(visitor, args);
            }
            return returnValue;
          } catch (InvocationTargetException e) {
            throw e.getTargetException();
          }
        }
      });
}
 
Example 8
Source File: ProductPartitionTree.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private ProductPartitionTree(final ProductPartitionTreeImpl impl) {
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(
          impl, AdWordsInternals.getInstance().getAdsUtilityRegistry()) {
        @Override
        public String toString() {
          return impl.toString();
        }
      };
  this.impl = Reflection.newProxy(ProductPartitionTreeInterface.class, invocationHandler);
}
 
Example 9
Source File: AdHocReportDownloadHelper.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Constructor used by Guice. */
@Inject
AdHocReportDownloadHelper(
    AdHocReportDownloadHelperImpl helperImpl, AdsUtilityRegistry adsUtilityRegistry) {
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(helperImpl, adsUtilityRegistry);
  this.impl = Reflection.newProxy(AdHocReportDownloadHelperInterface.class, invocationHandler);
}
 
Example 10
Source File: ServiceQuery.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Constructs a new service query builder. */
@SuppressWarnings("unchecked")
public Builder() {
  proxiedImpl = new ServiceQueryBuilderImpl(this);
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(
          proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry());
  this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler);
}
 
Example 11
Source File: SelectorBuilder.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public SelectorBuilder() {
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(
          new SelectorBuilderImpl(), AdWordsInternals.getInstance().getAdsUtilityRegistry());
  this.impl = Reflection.newProxy(SelectorBuilderInterface.class, invocationHandler);
}
 
Example 12
Source File: ApiCatalogImpl.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/** @inheritDoc */
@Override
public GoogleAdsAllVersions createAllVersionsClient(
    TransportChannelProvider provider, Credentials credentials) {
  Preconditions.checkNotNull(
      provider, "Transport channel provider required to create GoogleAdsAllVersions interface.");
  Preconditions.checkNotNull(
      credentials, "Credentials are required to create GoogleAdsAllVersions interface.");
  return Reflection.newProxy(
      GoogleAdsAllVersions.class,
      new GoogleAdsAllVersionsInvocationHandler(provider, credentials));
}
 
Example 13
Source File: PartitionAwareServiceFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
private S createDelegate(ServiceEndPoint endPoint) {
    final S delegateService = _delegate.create(endPoint);

    S proxiedService = Reflection.newProxy(_serviceClass, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                return method.invoke(delegateService, args);
            } catch (InvocationTargetException e) {
                // If the target exception is a declared exception then rethrow as-is
                Throwable targetException = e.getTargetException();
                for (Class<?> declaredException : method.getExceptionTypes()) {
                    // noinspection unchecked
                    Throwables.propagateIfInstanceOf(targetException, (Class<? extends Throwable>) declaredException);
                }
                // If the exception was due to connection issues and not necessarily the target let the caller know.
                // It's possible the connection timed out due to a problem on the target, but from our perspective
                // there's no definitive way of knowing.
                if (targetException instanceof ClientHandlerException) {
                    _errorMeter.mark();
                    throw new PartitionForwardingException("Failed to handle request at endpoint", targetException.getCause());
                }
                throw Throwables.propagate(targetException);
            }
        }
    });

    _proxiedToDelegateServices.put(proxiedService, delegateService);
    return proxiedService;
}
 
Example 14
Source File: AsyncTestRunner.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private Object createSuccessCallback(PromiseType promiseType) {
  return Reflection.newProxy(
      promiseType.successCallbackType,
      (proxy, method, args) -> {
        future.set(null);
        return args[0];
      });
}
 
Example 15
Source File: ServiceQuery.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new service query builder by copying all properties from the passed service
 * query builder.
 *
 * @param builderInterface the service query builder whose properties will be copied to.
 */
@SuppressWarnings("unchecked")
public Builder(BuilderInterface<Page, SortOrder> builderInterface) {
  checkNotNull(builderInterface, "The service query builder cannot be null.");
  Builder builder = (Builder) builderInterface;
  proxiedImpl = new ServiceQueryBuilderImpl(builder.proxiedImpl);
  InvocationHandler invocationHandler =
      new AdsUtilityInvocationHandler(
          proxiedImpl, AdWordsInternals.getInstance().getAdsUtilityRegistry());
  this.proxy = Reflection.newProxy(BuilderInterface.class, invocationHandler);
}
 
Example 16
Source File: ProxyFactory.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param strUrl  连接字符串
 * @param interfaceClass  接口类
 * @return
 */
private static Object createStandardProxy(Class<?> interfaceclass, String serviceName, Class<?> implMethod, LoadBalance balance) {
    InvocationHandler handler = new ProxyStandard(interfaceclass, serviceName, implMethod, balance);
    //        Object obj = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { interfaceclass }, handler);
    Object obj = Reflection.newProxy(interfaceclass, handler);
    logger.info(String.format("create jdkproxy for %s ", interfaceclass.getName()));
    return obj;
}
 
Example 17
Source File: GoogleAdsVersionFactory.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of interfaceSpec, an interface with accessor methods for all services
 * available in an API version.
 *
 * <p>The interfaceSpec class must be annotated with @VersionDescriptor.
 *
 * <p>All methods of interfaceSpec must be annotated with @ServiceClientDescriptor.
 */
public static <T> T createProxy(
    Class<T> interfaceSpec,
    TransportChannelProvider transportChannelProvider,
    Credentials credentials) {
  try {
    return Reflection.newProxy(
        interfaceSpec,
        new VersionDescriptorInvocationHandler(
            interfaceSpec, transportChannelProvider, credentials));
  } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
    throw new IllegalArgumentException("Invalid GoogleAdsVersion configuration", e);
  }
}
 
Example 18
Source File: ForeignMessageTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendForeignMessage() throws Exception
{
    final Destination replyTo = createQueue(getTestName() + "_replyTo");
    final Queue queue = createQueue(getTestName());
    final Connection connection = getConnection();
    try
    {
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final String jmsType = "TestJmsType";
        final String correlationId = "testCorrelationId";
        final ObjectMessage message = session.createObjectMessage();
        final ObjectMessage foreignMessage =
                Reflection.newProxy(ObjectMessage.class, new AbstractInvocationHandler()
                {
                    @Override
                    protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
                            throws Throwable
                    {
                        return method.invoke(message, args);
                    }
                });

        foreignMessage.setJMSCorrelationID(correlationId);
        foreignMessage.setJMSType(jmsType);
        foreignMessage.setJMSReplyTo(replyTo);
        Serializable payload = UUID.randomUUID();
        foreignMessage.setObject(payload);

        final MessageConsumer consumer = session.createConsumer(queue);
        final MessageProducer producer = session.createProducer(queue);
        producer.send(foreignMessage);

        connection.start();

        Message receivedMessage = consumer.receive(getReceiveTimeout());
        assertTrue("ObjectMessage was not received ", receivedMessage instanceof ObjectMessage);
        assertEquals("JMSCorrelationID mismatch",
                     foreignMessage.getJMSCorrelationID(),
                     receivedMessage.getJMSCorrelationID());
        assertEquals("JMSType mismatch", foreignMessage.getJMSType(), receivedMessage.getJMSType());
        assertEquals("JMSReply To mismatch", foreignMessage.getJMSReplyTo(), receivedMessage.getJMSReplyTo());
        assertEquals("JMSMessageID mismatch", foreignMessage.getJMSMessageID(), receivedMessage.getJMSMessageID());
        assertEquals("JMS Default priority should be default",
                     Message.DEFAULT_PRIORITY,
                     receivedMessage.getJMSPriority());
        assertEquals("Message payload not as expected", payload, ((ObjectMessage) receivedMessage).getObject());
    }
    finally
    {
        connection.close();
    }
}
 
Example 19
Source File: GeneratedDoesNotExistTest.java    From auto with Apache License 2.0 4 votes vote down vote up
private static <T> T partialProxy(Class<T> type, OverridableInvocationHandler<T> handler) {
  return Reflection.newProxy(type, handler);
}
 
Example 20
Source File: JSONMatrixReader.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private Pair<Iterator<Integer>, Supplier<SimpleCell[]>> parseToTable(CustomValue jsonNode) throws IOException {

        Table<Integer, String, SimpleCell> table = Reflection.newProxy(Table.class, new SafetyCheckInvocationHandler());

        for(CustomValue testCaseWrapper:jsonNode.getArrayValue()) {
            if (testCaseWrapper.getObjectValue().size() > 1) {
                throw new EPSCommonException("Too many nodes in testCase wrapper");
            }

            testCaseWrapper.getObjectValue().forEach((blockKey, commonBlock) -> {
                String commonBlockType = blockKey.getKey();
                AMLBlockBrace blockBrace = AMLBlockBrace.value(commonBlockType);

                Objects.requireNonNull(commonBlock, "'AML block' node must be presented");
                Objects.requireNonNull(blockBrace, "Unknown block type " + commonBlockType);

                int localRowCounter = tableRowCounter.getAndIncrement();
                table.put(localRowCounter, Column.Action.getName(), new SimpleCell(commonBlockType,blockKey.getLine()));

                commonBlock.getObjectValue().forEach((actionKey, actionNode) -> {
                    String reference = actionKey.getKey();

                    logger.debug("reading {}", reference);

                    if (actionNode.isObject()) {

                        int nestedCount = countNestedReferences(actionNode);
                        int target = tableRowCounter.get() + nestedCount;
                        table.put(target, Column.Reference.getName(), new SimpleCell(reference, actionKey.getLine()));
                        consumeNode(actionNode, table, target,  actionKey.getLine());
                        //FIXME will add additional empty row at last action
                        tableRowCounter.getAndIncrement();
                    } else if (!actionNode.isArray()) {
                        table.put(localRowCounter, reference,  new SimpleCell(actionNode.getSimpleValue().toString(), actionKey.getLine()));
                    } else{
                        throw new IllegalStateException(String.format("Invalid value type array %s found in block %s, number line %s", reference, commonBlockType, actionKey.getLine()));
                    }
                });

                table.put(tableRowCounter.getAndIncrement(), Column.Action.getName(), new SimpleCell(blockBrace.getInversed().getName(),blockKey.getLine()));
            });
        }

        Set<String> columns = ImmutableSet.<String>builder().addAll(table.columnKeySet()).add(Column.Id.getName()).build();
        columns.forEach(column -> table.put(0, column, new SimpleCell(column)));

        Iterator<Integer> rowIterator = dbg.DEBUG_SORT ? table.rowKeySet().iterator() : new TreeSet<>(table.rowKeySet()).iterator();

        Supplier<SimpleCell[]> supplier = SUPPLIER;
        //preserve header
        if (rowIterator.hasNext()) {

            supplier = () -> {
                int currentRow = rowIterator.next();
                Map<String, SimpleCell> row = new HashMap<>(table.row(currentRow));

                return columns.stream()
                        .map(key -> row.getOrDefault(key, new SimpleCell("")))
                        .toArray(SimpleCell[]::new);
            };
        }

        return new Pair<>(rowIterator, supplier);
    }