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.marvelution.bamboo.plugins.sonar.tasks.actions.admin.ConfigureSonarServers.java

/**
 * {@inheritDoc}/*from ww w. j  av  a2  s  .  c o  m*/
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    logger.debug("Got a " + proxy.getClass().getName() + " Proxy Invocation for " + method.getName());
    // Server methods
    if (proxy instanceof SonarServer) {
        if (method.getName().equals("getID")) {
            return getServerId();
        } else if (method.getName().equals("getName")) {
            return getServerName();
        } else if (method.getName().equals("getDescription")) {
            return getServerDescription();
        } else if (method.getName().equals("getHost")) {
            return getServerHost();
        } else if (method.getName().equals("getUsername")) {
            return getServerUsername();
        } else if (method.getName().equals("getPassword")) {
            return getServerPassword();
        } else if (method.getName().equals("getJDBCResource")) {
            return (JDBCResource) Proxy.newProxyInstance(JDBCResource.class.getClassLoader(),
                    new Class[] { JDBCResource.class }, this);
        }
        // JDBC Resource methods
    } else if (proxy instanceof JDBCResource) {
        if (method.getName().equals("getUrl")) {
            return getJdbcUrl();
        } else if (method.getName().equals("getDriver")) {
            return getJdbcDriver();
        } else if (method.getName().equals("getUsername")) {
            return getJdbcUsername();
        } else if (method.getName().equals("getPassword")) {
            return getJdbcPassword();
        }
    }
    return null;
}

From source file:org.apache.hama.ipc.AsyncRPC.java

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 * /* w  w w .  j  a  va 2  s  . c  o  m*/
 * @param protocol
 * @param clientVersion
 * @param addr
 * @param ticket
 * @param conf
 * @param factory
 * @param rpcTimeout
 * @param connectionRetryPolicy
 * @param checkVersion
 * @return the proxy
 * @throws IOException
 */
public static VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory,
        int rpcTimeout, RetryPolicy connectionRetryPolicy, boolean checkVersion) throws IOException {

    final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout,
            connectionRetryPolicy);
    VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, invoker);

    if (checkVersion) {
        checkVersion(protocol, clientVersion, proxy);
    }
    return proxy;
}

From source file:org.compass.spring.LocalCompassBean.java

public void afterPropertiesSet() throws Exception {
    CompassConfiguration config = this.config;
    if (config == null) {
        config = newConfiguration();/*  w  w  w.  j  av a2s.  c om*/
    }

    if (classLoader != null) {
        config.setClassLoader(getClassLoader());
    }

    if (this.configLocation != null) {
        config.configure(this.configLocation.getURL());
    }

    if (this.configLocations != null) {
        for (Resource configLocation1 : configLocations) {
            config.configure(configLocation1.getURL());
        }
    }

    if (this.mappingScan != null) {
        config.addScan(this.mappingScan);
    }

    if (this.compassSettings != null) {
        config.getSettings().addSettings(this.compassSettings);
    }

    if (this.settings != null) {
        config.getSettings().addSettings(this.settings);
    }

    if (resourceLocations != null) {
        for (Resource resourceLocation : resourceLocations) {
            config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename());
        }
    }

    if (resourceJarLocations != null) {
        for (Resource resourceJarLocation : resourceJarLocations) {
            config.addJar(resourceJarLocation.getFile());
        }
    }

    if (classMappings != null) {
        for (String classMapping : classMappings) {
            config.addClass(ClassUtils.forName(classMapping, getClassLoader()));
        }
    }

    if (resourceDirectoryLocations != null) {
        for (Resource resourceDirectoryLocation : resourceDirectoryLocations) {
            File file = resourceDirectoryLocation.getFile();
            if (!file.isDirectory()) {
                throw new IllegalArgumentException("Resource directory location [" + resourceDirectoryLocation
                        + "] does not denote a directory");
            }
            config.addDirectory(file);
        }
    }

    if (mappingResolvers != null) {
        for (InputStreamMappingResolver mappingResolver : mappingResolvers) {
            config.addMappingResolver(mappingResolver);
        }
    }

    if (convertersByName != null) {
        for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) {
            config.registerConverter(entry.getKey(), entry.getValue());
        }
    }
    if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) {
        config.getSettings().setSetting(CompassEnvironment.NAME, beanName);
    }

    if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) {
        config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath());
    }

    if (applicationContext != null) {
        String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
        for (String name : names) {
            try {
                PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext
                        .getBean(name);
                Method method = findMethod(propConfigurer.getClass(), "mergeProperties");
                method.setAccessible(true);
                Properties props = (Properties) method.invoke(propConfigurer);
                method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class);
                method.setAccessible(true);
                method.invoke(propConfigurer, props);
                method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class,
                        Properties.class, Set.class);
                method.setAccessible(true);
                String nullValue = null;
                try {
                    Field field = propConfigurer.getClass().getDeclaredField("nullValue");
                    field.setAccessible(true);
                    nullValue = (String) field.get(propConfigurer);
                } catch (NoSuchFieldException e) {
                    // no field (old spring version)
                }
                for (Map.Entry entry : config.getSettings().getProperties().entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    value = (String) method.invoke(propConfigurer, value, props, new HashSet());
                    config.getSettings().setSetting(key, value.equals(nullValue) ? null : value);
                }
            } catch (Exception e) {
                log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e);
            }
        }
    }

    // we do this after the proeprties placeholder hack, so if other Compass beans are created beacuse
    // of it, we still maintain the correct thread local setting of the data source and transaction manager
    if (dataSource != null) {
        ExternalDataSourceProvider.setDataSource(dataSource);
        if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) {
            config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS,
                    ExternalDataSourceProvider.class.getName());
        }
    }

    String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY);
    if (compassTransactionFactory == null && transactionManager != null) {
        // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one.
        config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY,
                SpringSyncTransactionFactory.class.getName());
    }
    if (compassTransactionFactory != null
            && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) {
        if (transactionManager == null) {
            throw new IllegalArgumentException(
                    "When using SpringSyncTransactionFactory the transactionManager property must be set");
        }
    }
    SpringSyncTransactionFactory.setTransactionManager(transactionManager);

    if (postProcessor != null) {
        postProcessor.process(config);
    }
    this.compass = newCompass(config);
    this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(),
            new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass));
}

From source file:org.apache.oozie.client.rest.JsonToBean.java

/**
 * Creates a workflow job bean from a JSON object.
 *
 * @param json json object./*from w  w w .  j  a v a 2 s .  co  m*/
 * @return a workflow job bean populated with the JSON object values.
 */
public static WorkflowJob createWorkflowJob(JSONObject json) {
    return (WorkflowJob) Proxy.newProxyInstance(JsonToBean.class.getClassLoader(),
            new Class[] { WorkflowJob.class }, new JsonInvocationHandler(WF_JOB, json));
}

From source file:cc.tooyoung.common.db.JdbcTemplate.java

/**
 * Create a close-suppressing proxy for the given JDBC Connection.
 * Called by the <code>execute</code> method.
 * <p>The proxy also prepares returned JDBC Statements, applying
 * statement settings such as fetch size, max rows, and query timeout.
 * @param con the JDBC Connection to create a proxy for
 * @return the Connection proxy/*  w  ww . j  a  va 2  s  .  c  o m*/
 * @see java.sql.Connection#close()
 * @see #execute(ConnectionCallback)
 * @see #applyStatementSettings
 */
protected Connection createConnectionProxy(DataSource dataSource, Connection con) {
    return (Connection) Proxy.newProxyInstance(ConnectionProxy.class.getClassLoader(),
            new Class[] { ConnectionProxy.class }, new CloseSuppressingInvocationHandler(dataSource, con));
}

From source file:org.rosenvold.spring.convention.ConventionBeanFactory.java

/**
 * Resolve the given autowiring value against the given required type,
 * e.g. an {@link org.springframework.beans.factory.ObjectFactory} value to its actual object result.
 *
 * @param autowiringValue the value to resolve
 * @param requiredType    the type to assign the result to
 * @return the resolved value/*w  w  w. j  av  a 2  s  . c  om*/
 */
public static Object resolveAutowiringValue(Object autowiringValue, Class requiredType) {
    if (autowiringValue instanceof ObjectFactory && !requiredType.isInstance(autowiringValue)) {
        ObjectFactory factory = (ObjectFactory) autowiringValue;
        if (autowiringValue instanceof Serializable && requiredType.isInterface()) {
            autowiringValue = Proxy.newProxyInstance(requiredType.getClassLoader(),
                    new Class[] { requiredType }, new ObjectFactoryDelegatingInvocationHandler(factory));
        } else {
            return factory.getObject();
        }
    }
    return autowiringValue;
}

From source file:org.apache.nifi.controller.ExtensionBuilder.java

private ControllerServiceNode createControllerServiceNode()
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, InitializationException {
    final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    try {/*from   w  ww.j  a  v  a  2s  . co m*/
        final Bundle bundle = extensionManager.getBundle(bundleCoordinate);
        if (bundle == null) {
            throw new IllegalStateException(
                    "Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate());
        }

        final ClassLoader detectedClassLoader = extensionManager.createInstanceClassLoader(type, identifier,
                bundle, classpathUrls == null ? Collections.emptySet() : classpathUrls);
        final Class<?> rawClass = Class.forName(type, true, detectedClassLoader);
        Thread.currentThread().setContextClassLoader(detectedClassLoader);

        final Class<? extends ControllerService> controllerServiceClass = rawClass
                .asSubclass(ControllerService.class);
        final ControllerService serviceImpl = controllerServiceClass.newInstance();
        final StandardControllerServiceInvocationHandler invocationHandler = new StandardControllerServiceInvocationHandler(
                extensionManager, serviceImpl);

        // extract all interfaces... controllerServiceClass is non null so getAllInterfaces is non null
        final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(controllerServiceClass);
        final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[0]);

        final ControllerService proxiedService;
        if (detectedClassLoader == null) {
            proxiedService = (ControllerService) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces,
                    invocationHandler);
        } else {
            proxiedService = (ControllerService) Proxy.newProxyInstance(detectedClassLoader, interfaces,
                    invocationHandler);
        }

        logger.info("Created Controller Service of type {} with identifier {}", type, identifier);
        final ComponentLog serviceLogger = new SimpleProcessLogger(identifier, serviceImpl);
        final TerminationAwareLogger terminationAwareLogger = new TerminationAwareLogger(serviceLogger);

        final StateManager stateManager = stateManagerProvider.getStateManager(identifier);
        final ControllerServiceInitializationContext initContext = new StandardControllerServiceInitializationContext(
                identifier, terminationAwareLogger, serviceProvider, stateManager, kerberosConfig);
        serviceImpl.initialize(initContext);

        final LoggableComponent<ControllerService> originalLoggableComponent = new LoggableComponent<>(
                serviceImpl, bundleCoordinate, terminationAwareLogger);
        final LoggableComponent<ControllerService> proxiedLoggableComponent = new LoggableComponent<>(
                proxiedService, bundleCoordinate, terminationAwareLogger);

        final ComponentVariableRegistry componentVarRegistry = new StandardComponentVariableRegistry(
                this.variableRegistry);
        final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(
                serviceProvider, componentVarRegistry);
        final ControllerServiceNode serviceNode = new StandardControllerServiceNode(originalLoggableComponent,
                proxiedLoggableComponent, invocationHandler, identifier, validationContextFactory,
                serviceProvider, componentVarRegistry, reloadComponent, extensionManager, validationTrigger);
        serviceNode.setName(rawClass.getSimpleName());

        invocationHandler.setServiceNode(serviceNode);
        return serviceNode;
    } finally {
        if (ctxClassLoader != null) {
            Thread.currentThread().setContextClassLoader(ctxClassLoader);
        }
    }
}

From source file:org.apache.htrace.core.Tracer.java

/**
 * Returns an object that will trace all calls to itself.
 *//*w  ww.  j  a v  a  2 s  . c  o m*/
@SuppressWarnings("unchecked")
<T, V> T createProxy(final T instance) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
            try (TraceScope scope = Tracer.this.newScope(method.getName());) {
                return method.invoke(instance, args);
            } catch (Throwable ex) {
                ex.printStackTrace();
                throw ex;
            }
        }
    };
    return (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), instance.getClass().getInterfaces(),
            handler);
}

From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBuilder.java

/**
 * Build the Hibernate {@code SessionFactory} through background bootstrapping,
 * using the given executor for a parallel initialization phase
 * (e.g. a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}).
 * <p>{@code SessionFactory} initialization will then switch into background
 * bootstrap mode, with a {@code SessionFactory} proxy immediately returned for
 * injection purposes instead of waiting for Hibernate's bootstrapping to complete.
 * However, note that the first actual call to a {@code SessionFactory} method will
 * then block until Hibernate's bootstrapping completed, if not ready by then.
 * For maximum benefit, make sure to avoid early {@code SessionFactory} calls
 * in init methods of related beans, even for metadata introspection purposes.
 *
 * @see #buildSessionFactory()//from   w  w w.j  a  v a2s  . co m
 * @since 4.3
 */
public SessionFactory buildSessionFactory(AsyncTaskExecutor bootstrapExecutor) {
    Assert.notNull(bootstrapExecutor, "AsyncTaskExecutor must not be null");
    return (SessionFactory) Proxy.newProxyInstance(this.resourcePatternResolver.getClassLoader(),
            new Class<?>[] { SessionFactoryImplementor.class, InfrastructureProxy.class },
            new BootstrapSessionFactoryInvocationHandler(bootstrapExecutor));
}

From source file:org.bytesoft.bytejta.supports.dubbo.spi.TransactionServiceFilter.java

public Result consumerInvokeForSVC(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RemoteCoordinatorRegistry remoteCoordinatorRegistry = RemoteCoordinatorRegistry.getInstance();
    TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();
    TransactionBeanFactory beanFactory = beanRegistry.getBeanFactory();
    RemoteCoordinator transactionCoordinator = beanFactory.getTransactionCoordinator();
    RemoteCoordinator consumeCoordinator = beanRegistry.getConsumeCoordinator();
    TransactionManager transactionManager = beanFactory.getTransactionManager();
    Transaction transaction = transactionManager.getTransactionQuietly();
    TransactionContext nativeTransactionContext = transaction == null ? null
            : transaction.getTransactionContext();

    URL targetUrl = invoker.getUrl();
    String targetAddr = targetUrl.getIp();
    String targetName = targetUrl.getParameter("application");
    int targetPort = targetUrl.getPort();
    String address = String.format("%s:%s:%s", targetAddr, targetName, targetPort);
    InvocationContext invocationContext = new InvocationContext();
    invocationContext.setServerHost(targetAddr);
    invocationContext.setServiceKey(targetName);
    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);//from  w w w  .j  a  v  a2s .c  o  m
        remoteCoordinatorRegistry.putTransactionManagerStub(address, remoteCoordinator);
    }

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

    TransactionResponseImpl response = new TransactionResponseImpl();
    response.setSourceTransactionCoordinator(remoteCoordinator);
    boolean success = true;
    try {
        this.beforeConsumerInvokeForSVC(invocation, request, response);
        RpcResult result = (RpcResult) invoker.invoke(invocation);
        Object value = result.getValue();
        if (InvocationResult.class.isInstance(value)) {
            InvocationResult wrapped = (InvocationResult) value;
            result.setValue(null);
            result.setException(null);

            if (wrapped.isFailure()) {
                result.setException(wrapped.getError());
            } else {
                result.setValue(wrapped.getValue());
            }

            String propagatedBy = (String) wrapped.getVariable(RemoteCoordinator.class.getName());
            String identifier = transactionCoordinator.getIdentifier();
            boolean participantDelistRequired = StringUtils.equals(propagatedBy, identifier) == false;
            response.setParticipantDelistFlag(participantDelistRequired);
            response.setParticipantEnlistFlag(request.isParticipantEnlistFlag());
        }
        return result;
    } catch (RpcException rex) {
        success = false;

        RpcResult result = new RpcResult();
        result.setException(rex);
        return result;
    } catch (Throwable rex) {
        success = false;
        logger.error("Error occurred in remote call!", rex);

        RpcResult result = new RpcResult();
        result.setException(new RpcException("Error occurred in remote call!", rex));
        return result;
    } finally {
        try {
            this.afterConsumerInvokeForSVC(invocation, request, response);
        } catch (RpcException rex) {
            if (success) {
                RpcResult result = new RpcResult();
                result.setException(rex);
                return result;
            }
        } catch (RuntimeException rex) {
            if (success) {
                logger.error("Error occurred in remote call!", rex);

                RpcResult result = new RpcResult();
                result.setException(new RpcException("Error occurred in remote call!", rex));
                return result;
            }
        }
    }

}