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.mirth.connect.client.core.Client.java

@SuppressWarnings("unchecked")
public <T> T getServlet(final Class<T> servletInterface, final ExecuteType executeType) {
    return (T) Proxy.newProxyInstance(
            AccessController.doPrivileged(ReflectionHelper.getClassLoaderPA(servletInterface)),
            new Class[] { servletInterface }, new InvocationHandler() {
                @Override//from w w  w .ja va 2  s  .c o  m
                public Object invoke(Object proxy, Method method, Object[] args) throws ClientException {
                    try {
                        WebTarget target = client.target(api);

                        Operation operation = OperationUtil.getOperation(servletInterface, method);
                        if (operation != null) {
                            target.property(ServerConnection.OPERATION_PROPERTY, operation);
                        }

                        if (executeType != null) {
                            target.property(ServerConnection.EXECUTE_TYPE_PROPERTY, executeType);
                        }

                        if (args == null && method.getName().equals("toString")) {
                            return target.toString();
                        }

                        T resource = WebResourceFactory.newResource(servletInterface, target);
                        Object result = method.invoke(resource, args);

                        // Make sure to return the right type
                        if (result == null && method.getReturnType().isPrimitive()) {
                            return method.getReturnType() == boolean.class ? false : (byte) 0x00;
                        }
                        return result;
                    } catch (Throwable t) {
                        Throwable cause = t;
                        if (cause instanceof InvocationTargetException && cause.getCause() != null) {
                            cause = cause.getCause();
                        }
                        if (cause instanceof ProcessingException && cause.getCause() != null) {
                            cause = cause.getCause();
                        }
                        if (cause instanceof ClientException) {
                            throw (ClientException) cause;
                        } else {
                            throw new ClientException(cause);
                        }
                    }
                }
            });
}

From source file:org.apache.hadoop.ipc.RPC.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public static VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory,
        int rpcTimeout) throws IOException {

    if (UserGroupInformation.isSecurityEnabled()) {
        SaslRpcServer.init(conf);/*from  ww w. ja v a 2  s  . c  om*/
    }
    VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout));
    long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion == clientVersion) {
        return proxy;
    } else {
        throw new VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }
}

From source file:org.amplafi.hivemind.factory.mock.MockBuilderFactoryImpl.java

/**
 * Method that calls the underlying applicationBuilderFactory
 * to create the real service.// w w w .jav  a2  s  .  c o  m
 * @param applicationBuilderFactory
 * @param factoryParameters
 * @return real service
 */
Object createCoreServiceImplementation(ServiceImplementationFactory applicationBuilderFactory,
        ServiceImplementationFactoryParameters factoryParameters) {
    Object createdObject;
    // wrap the parameters so that ModuleInterceptor
    // can always do it's thing.
    Module realModule = factoryParameters.getInvokingModule();
    ClassLoader loader = realModule.getClassResolver().getClassLoader();
    Module moduleWrapper = (Module) Proxy.newProxyInstance(loader, new Class[] { Module.class },
            new ModuleInterceptor(realModule));
    String serviceId = factoryParameters.getServiceId();
    ServicePoint servicePoint = realModule.getServicePoint(serviceId);
    ServiceImplementationFactoryParametersImpl replacement = new ServiceImplementationFactoryParametersImpl(
            servicePoint, moduleWrapper, factoryParameters.getParameters());
    createdObject = applicationBuilderFactory.createCoreServiceImplementation(replacement);
    return createdObject;
}

From source file:com.github.cherimojava.data.mongo.entity.EntityFactory.java

/**
 * Starting point to create a fluent API for query building
 * /*from w  ww.  j  ava2 s  .co m*/
 * @param clazz entity class to query
 * @param <E> entity class being queried
 * @return query start point
 */
public <E extends Entity> QueryStart<E> query(Class<E> clazz) {
    QueryInvocationHandler handler = new QueryInvocationHandler(clazz, getCollection(clazz),
            getProperties(clazz));
    QueryStart<E> query = (QueryStart<E>) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { QueryStart.class, OngoingQuery.class }, handler);
    handler.setProxy((OngoingQuery) query);
    return query;
}

From source file:org.apache.maven.index.cli.NexusIndexerCli.java

private void unpack(CommandLine cli, PlexusContainer plexus) throws ComponentLookupException, IOException {
    final String indexDirectoryName = cli.getOptionValue(INDEX, ".");
    final File indexFolder = new File(indexDirectoryName).getCanonicalFile();
    final File indexArchive = new File(indexFolder, IndexingContext.INDEX_FILE_PREFIX + ".gz");

    final String outputDirectoryName = cli.getOptionValue(TARGET_DIR, ".");
    final File outputFolder = new File(outputDirectoryName).getCanonicalFile();

    final boolean quiet = cli.hasOption(QUIET);
    if (!quiet) {
        System.err.printf("Index Folder:      %s\n", indexFolder.getAbsolutePath());
        System.err.printf("Output Folder:     %s\n", outputFolder.getAbsolutePath());
    }/*from w w w  .j a  v  a 2 s  .  c om*/

    long tstart = System.currentTimeMillis();

    final FSDirectory directory = FSDirectory.open(outputFolder);

    final List<IndexCreator> indexers = getIndexers(cli, plexus);

    BufferedInputStream is = null;
    try {
        is = new BufferedInputStream(new FileInputStream(indexArchive));
        DefaultIndexUpdater.unpackIndexData(is, directory,
                (IndexingContext) Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class[] { IndexingContext.class }, new PartialImplementation() {
                            public List<IndexCreator> getIndexCreators() {
                                return indexers;
                            }
                        })

        );
    } finally {
        IOUtil.close(is);
        if (directory != null) {
            directory.close();
        }
    }

    if (!quiet) {
        printStats(tstart);
    }
}

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

private ControllerServiceNode createGhostControllerService(final String type, final String id) {
    final InvocationHandler invocationHandler = new InvocationHandler() {
        @Override/*from  w  w  w .  j ava2s  .  c om*/
        public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
            final String methodName = method.getName();

            if ("validate".equals(methodName)) {
                final ValidationResult result = new ValidationResult.Builder().input("Any Property")
                        .subject("Missing Controller Service").valid(false)
                        .explanation(
                                "Controller Service could not be created because the Controller Service Type ("
                                        + type + ") could not be found")
                        .build();
                return Collections.singleton(result);
            } else if ("getPropertyDescriptor".equals(methodName)) {
                final String propertyName = (String) args[0];
                return new PropertyDescriptor.Builder().name(propertyName).description(propertyName)
                        .sensitive(true).required(true).build();
            } else if ("getPropertyDescriptors".equals(methodName)) {
                return Collections.emptyList();
            } else if ("onPropertyModified".equals(methodName)) {
                return null;
            } else if ("getIdentifier".equals(methodName)) {
                return id;
            } else if ("toString".equals(methodName)) {
                return "GhostControllerService[id=" + id + ", type=" + type + "]";
            } else if ("hashCode".equals(methodName)) {
                return 91 * type.hashCode() + 41 * id.hashCode();
            } else if ("equals".equals(methodName)) {
                return proxy == args[0];
            } else {
                throw new IllegalStateException(
                        "Controller Service could not be created because the Controller Service Type (" + type
                                + ") could not be found");
            }
        }
    };

    final ControllerService proxiedService = (ControllerService) Proxy.newProxyInstance(
            getClass().getClassLoader(), new Class[] { ControllerService.class }, invocationHandler);

    final String simpleClassName = type.contains(".") ? StringUtils.substringAfterLast(type, ".") : type;
    final String componentType = "(Missing) " + simpleClassName;

    final ComponentLog logger = new SimpleProcessLogger(id, proxiedService);

    final ControllerServiceNode serviceNode = new StandardControllerServiceNode(proxiedService, proxiedService,
            id, new StandardValidationContextFactory(this, variableRegistry), this, componentType, type,
            variableRegistry, logger);
    return serviceNode;
}

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

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 */// ww w  .ja v a  2  s  .co m
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 {

    if (UserGroupInformation.isSecurityEnabled()) {
        SaslRpcServer.init(conf);
    }
    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:mondrian.xmla.impl.Olap4jXmlaServlet.java

/**
 * Returns something that implements {@link OlapConnection} but still
 * behaves as the wrapper returned by the connection pool.
 *
 * <p>In other words we want the "close" method to play nice and do all the
 * pooling actions while we want all the olap methods to execute directly on
 * the un-wrapped OlapConnection object.
 */// ww  w .ja v a2s  .  c  o m
private static OlapConnection createDelegatingOlapConnection(final Connection connection,
        final OlapConnection olapConnection) {
    return (OlapConnection) Proxy.newProxyInstance(olapConnection.getClass().getClassLoader(),
            new Class[] { OlapConnection.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("unwrap".equals(method.getName())
                            || OlapConnection.class.isAssignableFrom(method.getDeclaringClass())) {
                        return method.invoke(olapConnection, args);
                    } else {
                        return method.invoke(connection, args);
                    }
                }
            });
}

From source file:org.amplafi.hivemind.factory.mock.MockBuilderFactoryImpl.java

/**
 * In interceptor factory mode, only knows how to create an interceptor for
 * BuilderFactory.//  ww  w . ja  va 2 s  .  c o m
 * @see org.apache.hivemind.ServiceInterceptorFactory#createInterceptor(org.apache.hivemind.InterceptorStack, org.apache.hivemind.internal.Module, java.util.List)
 */
@SuppressWarnings({ "unchecked" })
public void createInterceptor(InterceptorStack stack, Module invokingModule, List parameters) {
    Log log = stack.getServiceLog();

    ServiceImplementationFactory delegate = (ServiceImplementationFactory) stack.peek();
    InvocationHandler handler = new ServiceImplementationFactoryInterceptor(log, delegate);

    Object interceptor = Proxy.newProxyInstance(invokingModule.getClassResolver().getClassLoader(),
            new Class[] { stack.getServiceInterface() }, handler);

    stack.push(interceptor);
}

From source file:org.codice.ddf.itests.common.AbstractIntegrationTest.java

@SuppressWarnings({ "squid:S2696" /* writing to static ddfHome to share state between test methods */
})
@PostTestConstruct/*  w w w  .  j a va2  s  . co  m*/
public void initFacades() {
    ddfHome = System.getProperty(DDF_HOME_PROPERTY);
    adminConfig = new AdminConfig(configAdmin);

    // This proxy runs the service manager as the system subject
    serviceManager = (ServiceManager) Proxy.newProxyInstance(AbstractIntegrationTest.class.getClassLoader(),
            ServiceManagerImpl.class.getInterfaces(),
            new ServiceManagerProxy(new ServiceManagerImpl(metatype, adminConfig)));

    catalogBundle = new CatalogBundle(serviceManager, adminConfig);
    securityPolicy = new SecurityPolicyConfigurator(serviceManager, configAdmin);
    urlResourceReaderConfigurator = new UrlResourceReaderConfigurator(configAdmin);
    console = new KarafConsole(getServiceManager().getBundleContext(), features, sessionFactory);
}