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

/**
 * Internal method to get a {@link Proxy} for the {@link SonarServer}
 * This {@link Proxy} has the {@link ConfigureSonarServers} object as {@link InvocationHandler}
 * //from  ww  w  . j av  a2  s . c om
 * @return the {@link Proxy}
 */
private SonarServer getSonarServer() {
    return (SonarServer) Proxy.newProxyInstance(SonarServer.class.getClassLoader(),
            new Class[] { SonarServer.class }, this);
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

protected Object newDynamicProxy(Type type, final Map<String, Type> itestGenericMap,
        final ITestContext iTestContext) {
    final Class<?> clazz = ITestTypeUtil.getRawClass(type);
    final Map<String, Object> methodResults = new HashMap<String, Object>();

    Object res = Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {

                @Override/*from  w  w w .  j av  a2  s.c o  m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String mSignature = ITestUtils.getMethodSingnature(method, true);
                    if (methodResults.containsKey(mSignature)) {
                        return methodResults.get(mSignature);
                    }
                    throw new ITestMethodExecutionException(
                            "Implementation of " + clazz.getName() + "." + mSignature + " not provided", null);
                }
            });

    Map<String, Type> map = ITestTypeUtil.getTypeMap(type, new HashMap<String, Type>());

    Class<?> t = clazz;
    do {
        for (Method m : t.getDeclaredMethods()) {
            if (!Modifier.isStatic(m.getModifiers())) {
                String signature = ITestUtils.getMethodSingnature(m, true);
                ITestParamState iTestState = iTestContext.getCurrentParam();
                ITestParamState mITestState = iTestState == null ? null : iTestState.getElement(signature);
                if (null == mITestState) {
                    mITestState = iTestState == null ? null
                            : iTestState.getElement(signature = ITestUtils.getMethodSingnature(m, false));
                }
                fillMethod(m, res, signature, map, iTestContext, methodResults);
            }
        }
        map = ITestTypeUtil.getTypeMap(clazz, map);
    } while ((t = t.getSuperclass()) != null);

    return res;
}

From source file:org.hyperic.hq.product.jmx.MxUtil.java

public static JMXConnector getCachedMBeanConnector(Properties config)
        throws MalformedURLException, IOException {
    String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL);
    String user = config.getProperty(PROP_JMX_USERNAME);
    String pass = config.getProperty(PROP_JMX_PASSWORD);
    JMXConnectorKey key = new JMXConnectorKey(jmxUrl, user, pass);
    JMXConnector rtn = null;/*from  w  w  w.  j ava  2s  . c om*/
    synchronized (mbeanConns) {
        rtn = mbeanConns.get(key);
        if (rtn == null) {
            rtn = getMBeanConnector(config);
            mbeanConns.put(key, rtn);
        }
        try {
            // ensure that the connection is not broken
            rtn.getMBeanServerConnection();
        } catch (IOException e) {
            close(rtn);
            rtn = getMBeanConnector(config);
            mbeanConns.put(key, rtn);
        }
    }
    final JMXConnector c = rtn;
    final InvocationHandler handler = new InvocationHandler() {
        private final JMXConnector conn = c;

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("close")) {
                return null;
            }
            synchronized (conn) {
                return method.invoke(conn, args);
            }
        }
    };
    return (JMXConnector) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { JMXConnector.class }, handler);
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * Method postProcessBundleContext has to be overridden to wrap system
 * bundleContext into a fake one. Thanks to that installing bundle can be
 * intercepted and JunitTestActivator can be created and started.
 *///from ww  w  .j  av  a  2s .  com
@Override
protected void postProcessBundleContext(final BundleContext context) throws Exception {
    BundleContext fakeBC = (BundleContext) Proxy.newProxyInstance(BundleContext.class.getClassLoader(),
            new Class[] { BundleContext.class }, new FakeBundleContext(context));
    super.postProcessBundleContext(fakeBC);
}

From source file:lib.JdbcTemplate.java

/**
 * Create a close-suppressing proxy for the given JDBC Connection.
 * Called by the {@code execute} 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//from   ww  w. ja v  a2  s  . c  om
 * @see java.sql.Connection#close()
 * @see #execute(ConnectionCallback)
 * @see #applyStatementSettings
 */
protected Connection createConnectionProxy(Connection con) {
    return (Connection) Proxy.newProxyInstance(ConnectionProxy.class.getClassLoader(),
            new Class<?>[] { ConnectionProxy.class }, new CloseSuppressingInvocationHandler(con));
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

@SuppressWarnings("unchecked")
private <ModelType> Result<ModelType> internalCreateModel(Object adaptable, Class<ModelType> requestedType) {
    Result<ModelType> result;
    ThreadInvocationCounter threadInvocationCounter = invocationCountThreadLocal.get();
    if (threadInvocationCounter.isMaximumReached()) {
        String msg = String.format("Adapting %s to %s failed, too much recursive invocations (>=%s).",
                adaptable, requestedType, threadInvocationCounter.maxRecursionDepth);
        return new Result<ModelType>(new ModelClassException(msg));
    }//from   w w w  .j  a v a 2  s .c  o  m
    threadInvocationCounter.increase();
    try {
        // check if a different implementation class was registered for this adapter type
        ModelClass<ModelType> modelClass = getImplementationTypeForAdapterType(requestedType, adaptable);

        if (!modelClass.hasModelAnnotation()) {
            String msg = String.format("Provided Adapter class does not have a Model annotation: %s",
                    modelClass.getType());
            return new Result<ModelType>(new ModelClassException(msg));
        }
        boolean isAdaptable = false;

        Model modelAnnotation = modelClass.getModelAnnotation();
        Class<?>[] declaredAdaptable = modelAnnotation.adaptables();
        for (Class<?> clazz : declaredAdaptable) {
            if (clazz.isInstance(adaptable)) {
                isAdaptable = true;
            }
        }
        if (!isAdaptable) {
            String msg = String.format("Adaptables (%s) are not acceptable for the model class: %s",
                    StringUtils.join(declaredAdaptable), modelClass.getType());
            return new Result<ModelType>(new InvalidAdaptableException(msg));
        } else {
            RuntimeException t = validateModel(adaptable, modelClass.getType(), modelAnnotation);
            if (t != null) {
                return new Result<ModelType>(t);
            }
            if (modelClass.getType().isInterface()) {
                Result<InvocationHandler> handlerResult = createInvocationHandler(adaptable, modelClass);
                if (handlerResult.wasSuccessful()) {
                    ModelType model = (ModelType) Proxy.newProxyInstance(modelClass.getType().getClassLoader(),
                            new Class<?>[] { modelClass.getType() }, handlerResult.getValue());
                    result = new Result<ModelType>(model);
                } else {
                    return new Result<ModelType>(handlerResult.getThrowable());
                }
            } else {
                try {
                    result = createObject(adaptable, modelClass);
                } catch (Exception e) {
                    String msg = String.format("Unable to create model %s", modelClass.getType());
                    return new Result<ModelType>(new ModelClassException(msg, e));
                }
            }
        }
        return result;
    } finally {
        threadInvocationCounter.decrease();
    }
}

From source file:com.gh.bmd.jrt.android.v4.core.DefaultObjectContextRoutineBuilder.java

@Nonnull
public <TYPE> TYPE buildProxy(@Nonnull final Class<TYPE> itf) {

    if (!itf.isInterface()) {

        throw new IllegalArgumentException(
                "the specified class is not an interface: " + itf.getCanonicalName());
    }// w  w  w.  j ava 2s.c  o  m

    final RoutineConfiguration configuration = mConfiguration;

    if (configuration != null) {

        warn(configuration);
    }

    final Object proxy = Proxy.newProxyInstance(itf.getClassLoader(), new Class[] { itf },
            new ProxyInvocationHandler(this, itf));
    return itf.cast(proxy);
}

From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java

/**
 * Create a close-suppressing proxy for the given Hibernate Session. The
 * proxy also prepares returned Query and Criteria objects.
 *
 * @param session the Hibernate Session to create a proxy for
 * @return the Session proxy//from   w  w  w. j  a v a2 s .co  m
 * @see org.hibernate.Session#close()
 * @see #prepareQuery
 * @see #prepareCriteria
 */
protected Session createSessionProxy(Session session) {
    Class<?>[] sessionIfcs = null;
    Class<?> mainIfc = Session.class;
    if (session instanceof EventSource) {
        sessionIfcs = new Class[] { mainIfc, EventSource.class };
    } else if (session instanceof SessionImplementor) {
        sessionIfcs = new Class[] { mainIfc, SessionImplementor.class };
    } else {
        sessionIfcs = new Class[] { mainIfc };
    }
    return (Session) Proxy.newProxyInstance(session.getClass().getClassLoader(), sessionIfcs,
            new CloseSuppressingInvocationHandler(session));
}

From source file:com.meidusa.venus.client.VenusServiceFactory.java

private void loadConfiguration(Map<String, Tuple<ObjectPool, BackendConnectionPool>> poolMap,
        Map<Class<?>, Tuple<Object, RemotingInvocationHandler>> servicesMap,
        Map<Class<?>, ServiceConfig> serviceConfig, Map<String, Object> realPools) throws Exception {
    VenusClient all = new VenusClient();
    for (String configFile : configFiles) {
        configFile = (String) ConfigUtil.filter(configFile);
        URL url = this.getClass().getResource("venusClientRule.xml");
        if (url == null) {
            throw new VenusConfigException("venusClientRule.xml not found!,pls rebuild venus!");
        }/*from  ww  w  .java2 s  .c  o m*/
        RuleSet ruleSet = new FromXmlRuleSet(url, new DigesterRuleParser());
        Digester digester = new Digester();
        digester.setValidating(false);
        digester.addRuleSet(ruleSet);

        try {
            InputStream is = ResourceUtils.getURL(configFile.trim()).openStream();
            VenusClient venus = (VenusClient) digester.parse(is);
            for (ServiceConfig config : venus.getServiceConfigs()) {
                if (config.getType() == null) {
                    logger.error("Service type can not be null:" + configFile);
                    throw new ConfigurationException("Service type can not be null:" + configFile);
                }
            }
            all.getRemoteMap().putAll(venus.getRemoteMap());
            all.getServiceConfigs().addAll(venus.getServiceConfigs());
        } catch (Exception e) {
            throw new ConfigurationException("can not parser xml:" + configFile, e);
        }
    }

    // ? remotePool
    for (Map.Entry<String, Remote> entry : all.getRemoteMap().entrySet()) {
        RemoteContainer container = createRemoteContainer(entry.getValue(), realPools);
        Tuple<ObjectPool, BackendConnectionPool> tuple = new Tuple<ObjectPool, BackendConnectionPool>();
        tuple.left = container.getBioPool();
        tuple.right = container.getNioPool();
        poolMap.put(entry.getKey(), tuple);
    }

    for (ServiceConfig config : all.getServiceConfigs()) {

        Remote remote = all.getRemoteMap().get(config.getRemote());
        Tuple<ObjectPool, BackendConnectionPool> tuple = null;
        if (!StringUtil.isEmpty(config.getRemote())) {
            tuple = poolMap.get(config.getRemote());
            if (tuple == null) {
                throw new ConfigurationException("remote=" + config.getRemote() + " not found!!");
            }
        } else {
            String ipAddress = config.getIpAddressList();
            tuple = poolMap.get(ipAddress);
            if (ipAddress != null && tuple == null) {
                RemoteContainer container = createRemoteContainer(true, ipAddress, realPools);
                tuple = new Tuple<ObjectPool, BackendConnectionPool>();
                tuple.left = container.getBioPool();
                tuple.right = container.getNioPool();
                poolMap.put(ipAddress, tuple);
            }
        }

        if (tuple != null) {
            RemotingInvocationHandler invocationHandler = new RemotingInvocationHandler();
            invocationHandler.setBioConnPool(tuple.left);
            invocationHandler.setNioConnPool(tuple.right);
            invocationHandler.setServiceFactory(this);
            invocationHandler.setVenusExceptionFactory(this.getVenusExceptionFactory());
            if (remote != null && remote.getAuthenticator() != null) {
                invocationHandler.setSerializeType(remote.getAuthenticator().getSerializeType());
            }

            invocationHandler.setContainer(this.container);

            Object object = Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    new Class[] { config.getType() }, invocationHandler);

            for (Method method : config.getType().getMethods()) {
                Endpoint endpoint = method.getAnnotation(Endpoint.class);
                if (endpoint != null) {
                    Class[] eclazz = method.getExceptionTypes();
                    for (Class clazz : eclazz) {
                        if (venusExceptionFactory != null && CodedException.class.isAssignableFrom(clazz)) {
                            venusExceptionFactory.addException(clazz);
                        }
                    }
                }
            }

            serviceConfig.put(config.getType(), config);
            Tuple<Object, RemotingInvocationHandler> serviceTuple = new Tuple<Object, RemotingInvocationHandler>(
                    object, invocationHandler);
            servicesMap.put(config.getType(), serviceTuple);
            if (config.getBeanName() != null) {
                serviceBeanMap.put(config.getBeanName(), serviceTuple);
            }
        } else {
            if (config.getInstance() != null) {
                Tuple<Object, RemotingInvocationHandler> serviceTuple = new Tuple<Object, RemotingInvocationHandler>(
                        config.getInstance(), null);
                servicesMap.put(config.getType(), serviceTuple);
                if (config.getBeanName() != null) {
                    serviceBeanMap.put(config.getBeanName(), serviceTuple);
                }
            } else {
                throw new ConfigurationException(
                        "Service instance or ipAddressList or remote can not be null:" + config.getType());
            }
        }

    }
}

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

/**
 * Creates a workflow action bean from a JSON object.
 *
 * @param json json object./*from w  w w .  j ava 2 s .c o  m*/
 * @return a workflow action bean populated with the JSON object values.
 */
public static WorkflowAction createWorkflowAction(JSONObject json) {
    return (WorkflowAction) Proxy.newProxyInstance(JsonToBean.class.getClassLoader(),
            new Class[] { WorkflowAction.class }, new JsonInvocationHandler(WF_ACTION, json));
}