Example usage for java.lang.reflect Proxy newProxyInstance

List of usage examples for java.lang.reflect Proxy newProxyInstance

Introduction

In this page you can find the example usage for java.lang.reflect Proxy newProxyInstance.

Prototype

private static Object newProxyInstance(Class<?> caller, 
            Constructor<?> cons, InvocationHandler h) 

Source Link

Usage

From source file:com.netflix.amazoncomponents.security.AmazonClientProvider.java

protected <T extends AmazonWebServiceClient, U> U getThrottlingHandler(Class<U> interfaceKlazz, Class<T> impl,
        NetflixAmazonCredentials amazonCredentials, String region, boolean skipEdda) {
    try {//from   w  w  w. j  a  v a  2  s  .c om
        T delegate = getClient(impl, amazonCredentials, region);
        U client = (U) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { interfaceKlazz },
                new ThrottledAmazonClientInvocationHandler(delegate, retryCallback));
        if (amazonCredentials.getEddaEnabled() && !skipEdda) {
            return (U) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { interfaceKlazz },
                    getInvocationHandler(client, delegate.getServiceName(), region, amazonCredentials));
        } else {
            return client;
        }
    } catch (Exception e) {
        throw new RuntimeException("Instantiation of client implementation failed!", e);
    }
}

From source file:org.apache.olingo.ext.proxy.commons.AbstractStructuredInvocationHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (method.getName().startsWith("get")) {
        // Here need check "get"/"set" first for better get-/set- performance because
        // the below if-statements are really time-consuming, even twice slower than "get" body.

        // Assumption: for each getter will always exist a setter and viceversa.
        // get method annotation and check if it exists as expected

        final Object res;
        final Method getter = typeRef.getMethod(method.getName());

        final Property property = ClassUtils.getAnnotation(Property.class, getter);
        if (property == null) {
            final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter);
            if (navProp == null) {
                throw new UnsupportedOperationException("Unsupported method " + method.getName());
            } else {
                // if the getter refers to a navigation property ... navigate and follow link if necessary
                res = getNavigationPropertyValue(navProp, getter);
            }/*w w  w  .  ja  v  a2s.  com*/
        } else {
            // if the getter refers to a property .... get property from wrapped entity
            res = getPropertyValue(property.name(), getter.getGenericReturnType());
        }

        return res;
    } else if (method.getName().startsWith("set")) {
        // get the corresponding getter method (see assumption above)
        final String getterName = method.getName().replaceFirst("set", "get");
        final Method getter = typeRef.getMethod(getterName);

        final Property property = ClassUtils.getAnnotation(Property.class, getter);
        if (property == null) {
            final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter);
            if (navProp == null) {
                throw new UnsupportedOperationException("Unsupported method " + method.getName());
            } else {
                // if the getter refers to a navigation property ... 
                if (ArrayUtils.isEmpty(args) || args.length != 1) {
                    throw new IllegalArgumentException("Invalid argument");
                }

                setNavigationPropertyValue(navProp, args[0]);
            }
        } else {
            setPropertyValue(property, args[0]);
        }

        return ClassUtils.returnVoid();
    } else if ("expand".equals(method.getName()) || "select".equals(method.getName())
            || "refs".equals(method.getName())) {
        invokeSelfMethod(method, args);
        return proxy;
    } else if (isSelfMethod(method)) {
        return invokeSelfMethod(method, args);
    } else if ("load".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        load();
        return proxy;
    } else if ("loadAsync".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        return service.getClient().getConfiguration().getExecutor().submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                load();
                return proxy;
            }
        });
    } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        final Class<?> returnType = method.getReturnType();

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { returnType }, OperationInvocationHandler.getInstance(getEntityHandler()));
    } else if ("annotations".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        final Class<?> returnType = method.getReturnType();

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { returnType },
                AnnotatationsInvocationHandler.getInstance(getEntityHandler(), this));
    } else {
        throw new NoSuchMethodException(method.getName());
    }
}

From source file:com.vmware.upgrade.factory.CompositeUpgradeDefinitionFactory.java

/**
 * {@inheritDoc}/*from w w  w . jav a  2  s  . c  om*/
 *
 * @return an {@link UpgradeDefinition} containing the union of those returned by the delegates
 */
@Override
public UpgradeDefinition create(final UpgradeContext context) throws IOException {
    final List<Task> upgradeTasks = new ArrayList<Task>();

    // When using an index based version filter, the indexed needs to be tracked
    int indexCount = 0;

    /*
     *  Create a task representing all of the workload for each of the definitionFactories. Each
     *  holds a SerialAggregateTask that contains all of the workload of a single
     *  UpgradeDefinitionFactory.
     */
    for (final UpgradeDefinitionFactoryRef factoryRef : definitionFactoryRefs) {
        final VersionFilter versionFilter;

        if (ordered) {
            versionFilter = new VersionFilter.IndexBasedVersionFilter(indexCount);
            indexCount++;
        } else {
            versionFilter = new VersionFilter.KeyBasedVersionFilter(factoryRef.getName());
        }

        final Object proxy = Proxy.newProxyInstance(UpgradeContext.class.getClassLoader(),
                new Class[] { UpgradeContext.class }, new ProxyUpgradeContext(context, versionFilter));

        final UpgradeContext filteredContext = (UpgradeContext) proxy;

        final UpgradeDefinition delegateUpgradeDefinition = factoryRef.getFactory().create(filteredContext);
        final List<Task> delegateUpgradeTasks = delegateUpgradeDefinition.getUpgradeTasks();
        upgradeTasks.add(new SerialAggregateTask(filteredContext, factoryRef.getName(), delegateUpgradeTasks));
    }

    return new UpgradeDefinition() {
        @Override
        public List<Task> getUpgradeTasks() {
            return Collections.unmodifiableList(upgradeTasks);
        }
    };
}

From source file:org.apache.brooklyn.rest.client.BrooklynApi.java

@SuppressWarnings("unchecked")
private <T> T proxy(Class<T> clazz) {
    final T result0 = ProxyFactory.create(clazz, target, clientExecutor);
    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {
                @Override//from  w w  w  .  j  a va  2  s . c  o  m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        Object result1 = method.invoke(result0, args);
                        Class<?> type = String.class;
                        if (result1 instanceof Response) {
                            Response resp = (Response) result1;
                            if (isStatusCodeHealthy(resp.getStatus())
                                    && method.isAnnotationPresent(ApiOperation.class)) {
                                type = getClassFromMethodAnnotationOrDefault(method, type);
                            }
                            // wrap the original response so it self-closes
                            result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type);
                        }
                        return result1;
                    } catch (Throwable e) {
                        if (e instanceof InvocationTargetException) {
                            // throw the original exception
                            e = ((InvocationTargetException) e).getTargetException();
                        }
                        throw Exceptions.propagate(e);
                    }
                }

                private boolean isStatusCodeHealthy(int code) {
                    return (code >= 200 && code <= 299);
                }

                private Class<?> getClassFromMethodAnnotationOrDefault(Method method, Class<?> def) {
                    Class<?> type;
                    try {
                        type = method.getAnnotation(ApiOperation.class).response();
                    } catch (Exception e) {
                        type = def;
                        LOG.debug("Unable to get class from annotation: {}.  Defaulting to {}", e.getMessage(),
                                def.getName());
                        Exceptions.propagateIfFatal(e);
                    }
                    return type;
                }
            });
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * IWebAction?//from  w w  w  .ja  v a 2 s .  c  om
 * @param methodName ??
 * @param bean ?Bean
 * @return
 */
public static IWebAction createProxyAction(final Module module, final Object bean) {
    String methodName = module.getMethod();
    int argNum = 0;
    Method method = null;
    try {
        method = bean.getClass().getMethod(methodName);
    } catch (NoSuchMethodException nme) {
        try {
            method = bean.getClass().getMethod(methodName, WebForm.class);
            argNum = 1;
        } catch (NoSuchMethodException e) {
            try {
                method = bean.getClass().getMethod(methodName, WebForm.class, Module.class);
                argNum = 2;
            } catch (NoSuchMethodException e2) {
                e.printStackTrace();
            }
        }
    }
    final Method beanMethod = method;
    final int num = argNum;
    if (method != null) {
        return (IWebAction) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[] { IWebAction.class }, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (method.getName().equals("execute")) {
                            Object[] arg;
                            if (num == 0)
                                arg = new Object[] {};
                            else if (num == 1)
                                arg = new Object[] { args[0] };
                            else
                                arg = args;
                            Object result = beanMethod.invoke(bean, arg);
                            if (result != null) {
                                if (result instanceof Page)
                                    return result;
                                else
                                    return module.findPage(result.toString());
                            }
                            return null;
                        }
                        return method.invoke(bean, args);
                    }
                });
    }
    return null;
}

From source file:org.apache.nifi.controller.service.StandardControllerServiceProvider.java

@Override
public ControllerServiceNode createControllerService(final String type, final String id,
        final boolean firstTimeAdded) {
    if (type == null || id == null) {
        throw new NullPointerException();
    }/*from  w ww .  j  a v a 2s  . c om*/

    final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final ClassLoader cl = ExtensionManager.getClassLoader(type, id);
        final Class<?> rawClass;

        try {
            if (cl == null) {
                rawClass = Class.forName(type);
            } else {
                Thread.currentThread().setContextClassLoader(cl);
                rawClass = Class.forName(type, false, cl);
            }
        } catch (final Exception e) {
            logger.error("Could not create Controller Service of type " + type + " for ID " + id
                    + "; creating \"Ghost\" implementation", e);
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
            return createGhostControllerService(type, id);
        }

        final Class<? extends ControllerService> controllerServiceClass = rawClass
                .asSubclass(ControllerService.class);

        final ControllerService originalService = controllerServiceClass.newInstance();
        final AtomicReference<ControllerServiceNode> serviceNodeHolder = new AtomicReference<>(null);
        final InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args)
                    throws Throwable {

                final String methodName = method.getName();
                if ("initialize".equals(methodName) || "onPropertyModified".equals(methodName)) {
                    throw new UnsupportedOperationException(
                            method + " may only be invoked by the NiFi framework");
                }

                final ControllerServiceNode node = serviceNodeHolder.get();
                final ControllerServiceState state = node.getState();
                final boolean disabled = state != ControllerServiceState.ENABLED; // only allow method call if service state is ENABLED.
                if (disabled && !validDisabledMethods.contains(method)) {
                    // Use nar class loader here because we are implicitly calling toString() on the original implementation.
                    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(
                            originalService.getClass(), originalService.getIdentifier())) {
                        throw new IllegalStateException("Cannot invoke method " + method
                                + " on Controller Service " + originalService.getIdentifier()
                                + " because the Controller Service is disabled");
                    } catch (final Throwable e) {
                        throw new IllegalStateException(
                                "Cannot invoke method " + method + " on Controller Service with identifier "
                                        + id + " because the Controller Service is disabled");
                    }
                }

                try (final NarCloseable narCloseable = NarCloseable
                        .withComponentNarLoader(originalService.getClass(), originalService.getIdentifier())) {
                    return method.invoke(originalService, args);
                } catch (final InvocationTargetException e) {
                    // If the ControllerService throws an Exception, it'll be wrapped in an InvocationTargetException. We want
                    // to instead re-throw what the ControllerService threw, so we pull it out of the InvocationTargetException.
                    throw e.getCause();
                }
            }
        };

        final ControllerService proxiedService;
        if (cl == null) {
            proxiedService = (ControllerService) Proxy.newProxyInstance(getClass().getClassLoader(),
                    getInterfaces(controllerServiceClass), invocationHandler);
        } else {
            proxiedService = (ControllerService) Proxy.newProxyInstance(cl,
                    getInterfaces(controllerServiceClass), invocationHandler);
        }
        logger.info("Created Controller Service of type {} with identifier {}", type, id);

        final ComponentLog serviceLogger = new SimpleProcessLogger(id, originalService);
        originalService.initialize(new StandardControllerServiceInitializationContext(id, serviceLogger, this,
                getStateManager(id), nifiProperties));

        final ComponentLog logger = new SimpleProcessLogger(id, originalService);
        final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(this,
                variableRegistry);

        final ControllerServiceNode serviceNode = new StandardControllerServiceNode(proxiedService,
                originalService, id, validationContextFactory, this, variableRegistry, logger);
        serviceNodeHolder.set(serviceNode);
        serviceNode.setName(rawClass.getSimpleName());

        if (firstTimeAdded) {
            try (final NarCloseable x = NarCloseable.withComponentNarLoader(originalService.getClass(),
                    originalService.getIdentifier())) {
                ReflectionUtils.invokeMethodsWithAnnotation(OnAdded.class, originalService);
            } catch (final Exception e) {
                throw new ComponentLifeCycleException(
                        "Failed to invoke On-Added Lifecycle methods of " + originalService, e);
            }
        }

        return serviceNode;
    } catch (final Throwable t) {
        throw new ControllerServiceInstantiationException(t);
    } finally {
        if (currentContextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
        }
    }
}

From source file:org.eclipse.wb.internal.rcp.model.rcp.ActionBarAdvisorInfo.java

/**
 * Prepares {@link IActionBarConfigurer} implementation in {@link #m_IActionBarConfigurer}.
 *//*from  www  . j  ava  2  s.c  om*/
private void prepare_IActionBarConfigurer() throws ClassNotFoundException {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> class_IActionBarConfigurer = editorLoader
            .loadClass("org.eclipse.ui.application.IActionBarConfigurer");
    Class<?> class_IWorkbenchWindowConfigurer = editorLoader
            .loadClass("org.eclipse.ui.application.IWorkbenchWindowConfigurer");
    m_IActionBarConfigurer = Proxy.newProxyInstance(editorLoader, new Class<?>[] { class_IActionBarConfigurer },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodSignature = ReflectionUtils.getMethodSignature(method);
                    if (methodSignature.equals("getWindowConfigurer()")) {
                        return m_IWorkbenchWindowConfigurer;
                    }
                    if (methodSignature.equals("getCoolBarManager()")) {
                        return m_coolBarManager;
                    }
                    if (methodSignature.equals("getMenuManager()")) {
                        return m_menuManager;
                    }
                    throw new NotImplementedException(methodSignature);
                }
            });
    m_IWorkbenchWindowConfigurer = Proxy.newProxyInstance(editorLoader,
            new Class<?>[] { class_IWorkbenchWindowConfigurer }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodSignature = ReflectionUtils.getMethodSignature(method);
                    if (methodSignature.equals("getWindow()")) {
                        return m_IWorkbenchWindow;
                    }
                    throw new NotImplementedException(methodSignature);
                }
            });
    m_IWorkbenchWindow = DesignerPlugin.getActiveWorkbenchWindow();
}

From source file:org.bytesoft.bytetcc.supports.dubbo.spi.CompensableServiceFilter.java

public Result consumerInvoke(Invoker<?> invoker, Invocation invocation) throws RpcException, RemotingException {
    RemoteCoordinatorRegistry remoteCoordinatorRegistry = RemoteCoordinatorRegistry.getInstance();
    CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
    CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
    RemoteCoordinator consumeCoordinator = beanRegistry.getConsumeCoordinator();
    CompensableManager transactionManager = beanFactory.getCompensableManager();
    Transaction transaction = transactionManager.getCompensableTransactionQuietly();
    TransactionContext nativeTransactionContext = transaction == null ? null
            : transaction.getTransactionContext();

    URL targetUrl = invoker.getUrl();
    String targetAddr = targetUrl.getIp();
    int targetPort = targetUrl.getPort();
    String address = String.format("%s:%s", targetAddr, targetPort);
    InvocationContext invocationContext = new InvocationContext();
    invocationContext.setServerHost(targetAddr);
    invocationContext.setServerPort(targetPort);

    RemoteCoordinator remoteCoordinator = remoteCoordinatorRegistry.getTransactionManagerStub(address);
    if (remoteCoordinator == null) {
        DubboRemoteCoordinator dubboCoordinator = new DubboRemoteCoordinator();
        dubboCoordinator.setInvocationContext(invocationContext);
        dubboCoordinator.setRemoteCoordinator(consumeCoordinator);

        remoteCoordinator = (RemoteCoordinator) Proxy.newProxyInstance(
                DubboRemoteCoordinator.class.getClassLoader(), new Class[] { RemoteCoordinator.class },
                dubboCoordinator);//  www  .  ja v a  2s .c o  m
        remoteCoordinatorRegistry.putTransactionManagerStub(address, remoteCoordinator);
    }

    TransactionRequestImpl request = new TransactionRequestImpl();
    request.setTransactionContext(nativeTransactionContext);
    request.setTargetTransactionCoordinator(remoteCoordinator);

    TransactionResponseImpl response = new TransactionResponseImpl();
    response.setSourceTransactionCoordinator(remoteCoordinator);
    try {
        this.beforeConsumerInvoke(invocation, request, response);
        return invoker.invoke(invocation);
    } catch (RemotingException rex) {
        throw rex;
    } catch (RuntimeException rex) {
        logger.error("Error occurred in remote call!", rex);
        throw new RemotingException(rex.getMessage());
    } finally {
        this.afterConsumerInvoke(invocation, request, response);
    }

}

From source file:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java

@Test
public void testExpectedSubExceptionHandling() throws Exception {
    PoolableObjectFactory<Object> factory = makeMockFactory();
    ObjectPool<Object> pool = spy(new StackObjectPool<Object>(factory));
    PoolingHandler handler = new PoolingHandler(pool);
    class SubException extends IllegalArgumentException {
        private static final long serialVersionUID = 1L;
    }/*from w  ww . jav a2 s  . com*/
    handler.getValidExceptions().add(SubException.class);
    ITestClient proxy = (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { ITestClient.class }, handler);
    try {
        proxy.doSomethingBad(0);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    verify(pool, times(1)).borrowObject();
    verify(pool, times(0)).returnObject(any());
    verify(factory, times(1)).destroyObject(any());
}

From source file:net.big_oh.common.jdbc.JdbcDriverProxy.java

public Connection connect(String url, Properties connectionProperties) throws SQLException {
    Driver delegateDriver = lookupDelegateDriver(url);

    if (delegateDriver == null) {
        // return null per the API guidelines
        return null;
    }/*from  w w w.  j ava 2  s  . c  o m*/

    url = stripJdbcObserverPrefixFromUrl(url);

    ConnectionInstantiationEvent connectionInstantiationEvent = new ConnectionInstantiationEvent(this,
            delegateDriver, url, connectionProperties);

    for (JDBCEventListener listener : listeners) {
        try {
            listener.connectionRequested(connectionInstantiationEvent);
        } catch (RuntimeException rte) {
            logger.error(rte);
        }
    }

    Connection newConnection = delegateDriver.connect(url, connectionProperties);

    if (newConnection == null) {
        throw new SQLException("Failed to connect to url '" + url + "' using delegate driver "
                + delegateDriver.getClass().getName());
    }

    // Create a proxy for the returned connection
    boolean newConnectionInterfacesContainsConnection = Arrays.asList(newConnection.getClass().getInterfaces())
            .contains(Connection.class);
    Class<?>[] interfaces = new Class<?>[(newConnection.getClass().getInterfaces().length
            + ((newConnectionInterfacesContainsConnection) ? 0 : 1))];
    System.arraycopy(newConnection.getClass().getInterfaces(), 0, interfaces, 0,
            newConnection.getClass().getInterfaces().length);
    if (!newConnectionInterfacesContainsConnection) {
        interfaces[newConnection.getClass().getInterfaces().length] = Connection.class;
    }
    Connection connectionProxy = (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            interfaces, new JdbcObserverProxyConnectionInvocationHandler(newConnection, listeners));

    for (JDBCEventListener listener : listeners) {
        try {
            listener.connectionInstantiated(connectionInstantiationEvent, connectionProxy);
        } catch (RuntimeException rte) {
            logger.error(rte);
        }
    }

    return connectionProxy;
}