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:be.fgov.kszbcss.rhq.websphere.mbean.MBeanClient.java

public <T> T getProxy(Class<T> iface) {
    synchronized (proxies) {
        Object proxy = proxies.get(iface);
        if (proxy == null) {
            if (log.isDebugEnabled()) {
                log.debug("Creating dynamic proxy for MBean " + locator);
            }//  w w  w.jav  a  2s  .c  om
            for (Method method : iface.getMethods()) {
                if (!throwsException(method, JMException.class)
                        || !throwsException(method, ConnectorException.class)) {
                    throw new IllegalArgumentException(iface.getName() + " is not a valid proxy class: method "
                            + method.getName() + " must declare JMException and ConnectorException");
                }
            }
            proxy = Proxy.newProxyInstance(MBeanClient.class.getClassLoader(),
                    new Class<?>[] { iface, MBeanClientProxy.class }, new MBeanClientInvocationHandler(this));
            proxies.put(iface, proxy);
        }
        return iface.cast(proxy);
    }
}

From source file:org.apache.blur.thrift.AsyncClientPool.java

/**
 * Gets a client instance that implements the AsyncIface interface that
 * connects to the given connection string.
 * //w  ww  . j a v a 2  s  . co m
 * @param <T>
 * @param asyncIfaceClass
 *          the AsyncIface interface to pool.
 * @param connectionStr
 *          the connection string.
 * @return the client instance.
 */
@SuppressWarnings("unchecked")
public <T> T getClient(final Class<T> asyncIfaceClass, final String connectionStr) {
    List<Connection> connections = BlurClientManager.getConnections(connectionStr);
    Collections.shuffle(connections, random);
    // randomness ftw
    final Connection connection = connections.get(0);
    return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return execute(new AsyncCall(asyncIfaceClass, method, args, connection));
                }
            });
}

From source file:net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst.java

public ASTInput buildDFA(String plsqlCode) {
    LanguageVersionHandler languageVersionHandler = LanguageRegistry.getLanguage(PLSQLLanguageModule.NAME)
            .getDefaultVersion().getLanguageVersionHandler();
    ASTInput cu = (ASTInput) languageVersionHandler.getParser(languageVersionHandler.getDefaultParserOptions())
            .parse(null, new StringReader(plsqlCode));
    PLSQLParserVisitor jpv = (PLSQLParserVisitor) Proxy.newProxyInstance(
            PLSQLParserVisitor.class.getClassLoader(), new Class[] { PLSQLParserVisitor.class },
            new Collector<>(ASTInput.class));
    jpv.visit(cu, null);/*from  www  . j a v a2  s. c o  m*/
    new SymbolFacade().initializeWith(cu);
    new DataFlowFacade().initializeWith(languageVersionHandler.getDataFlowHandler(), cu);
    return cu;
}

From source file:org.blocks4j.reconf.client.proxy.ConfigurationRepositoryFactory.java

private static synchronized <T> T newInstance(Class<T> arg, ConfigurationRepositoryElement repo) {
    ConfigurationRepositoryFactory factory = new ConfigurationRepositoryFactory();
    ConfigurationRepositoryUpdater thread = new ConfigurationRepositoryUpdater(repo,
            ServiceLocator.defaultImplementation, factory);
    Environment.addThreadToCheck(thread);
    thread.start();//  w w w .  j a  v a2 s.  co m
    return (T) Proxy.newProxyInstance(arg.getClassLoader(), new Class<?>[] { arg }, factory);
}

From source file:org.apache.olingo.ext.proxy.utils.ProxyUtils.java

public static Object getComplexProxy(final AbstractService<?> service, final String name,
        final ClientValue value, final Class<?> ref, final EntityInvocationHandler handler, final URI baseURI,
        final boolean collectionItem) {

    final URIBuilder targetURI;
    if (collectionItem) {
        targetURI = null;/*w  ww  . j a v a 2  s.com*/
    } else {
        targetURI = baseURI == null ? null
                : service.getClient().newURIBuilder(baseURI.toASCIIString()).appendPropertySegment(name);
    }

    final ComplexInvocationHandler complexHandler;
    Class<?> actualRef = ref;
    if (value == null) {
        complexHandler = ComplexInvocationHandler.getInstance(actualRef, service, targetURI);
    } else {
        actualRef = CoreUtils.getComplexTypeRef(service, value); // handle derived types
        complexHandler = ComplexInvocationHandler.getInstance(value.asComplex(), actualRef, service, targetURI);
    }

    complexHandler.setEntityHandler(handler);

    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { actualRef },
            complexHandler);
}

From source file:org.kuali.rice.kns.web.struts.form.pojo.PojoPluginTest.java

@Test
public void testUndefinedOJBClass() {
    final Object notAnOjbObject = new HashMap();
    // stub out the persistence service
    PojoPropertyUtilsBean.PersistenceStructureServiceProvider.persistenceStructureService = (PersistenceStructureService) Proxy
            .newProxyInstance(this.getClass().getClassLoader(),
                    new Class[] { PersistenceStructureService.class }, new InvocationHandler() {
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if ("listCollectionObjectTypes".equals(method.getName())) {
                                return new HashMap();
                            }//  ww  w .  java 2 s  .co m
                            return null;
                        }
                    });
    assertNull(new PojoPropertyUtilsBean.PersistenceStructureServiceProvider()
            .getCollectionItemClass(notAnOjbObject, "abcd"));
}

From source file:com.fortify.processrunner.context.Context.java

/**
 * Make the contents of this {@link Context} instance available through the
 * given interface, allowing for type-safe access.
 * @param iface/*w  ww  .  ja v a2  s.com*/
 * @return
 */
public final <T> T as(Class<T> iface) {
    T result = (T) proxies.get(iface);
    if (result == null) {
        result = (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { iface },
                new MapBasedInvocationHandler(this));
    }
    return result;
}

From source file:be.fgov.kszbcss.rhq.websphere.process.WebSphereServer.java

public WebSphereServer(String cell, String node, String server, String processType,
        ProcessLocator processLocator) {
    this.processLocator = processLocator;

    // Notes:/*from   w  w  w. j  a  v  a  2 s  .  c om*/
    //  * The stats collection wrapper is applied before security because the security wrapper may rearrange
    //    some invocations, but we want the statistics to be as accurate as possible.
    //  * Process identity validation is handled after security because the ProcessIdentityValidator may
    //    prematurely create the AdminClient on a different thread.
    //  * The fail-fast feature is added last.
    processIdentityValidator = new ProcessIdentityValidator(
            new SecureAdminClientProvider(
                    new StatsCollectingAdminClientProvider(processLocator, AdminClientStatsCollector.INSTANCE)),
            cell, node, server, processType);
    adminClient = (AdminClient) Proxy.newProxyInstance(WebSphereServer.class.getClassLoader(),
            new Class<?>[] { AdminClient.class },
            new LazyAdminClientInvocationHandler(new FailFastAdminClientProvider(processIdentityValidator)));

    pidWatcher = new PIDWatcher(adminClient);
    pmiConfigRefreshTracker = pidWatcher.createTracker();

    notificationListenerManager = new NotificationListenerManager(adminClient, pidWatcher);
    mbeanClientFactory = new MBeanClientFactory(this);
    serverMBean = getMBeanClient(new MBeanLocator() {
        public Set<ObjectName> queryNames(WebSphereServer server) throws JMException, ConnectorException {
            return Collections.singleton(server.getAdminClient().getServerMBean());
        }
    });
    perf = getMBeanClient("WebSphere:type=Perf,*").getProxy(Perf.class);
}

From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java

private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request))
        return request;

    final Map<String, String> requestParams = new HashMap<String, String>();
    List<FileItemStream> listFiles = new ArrayList<FileItemStream>();

    // Parse the request
    ServletFileUpload sfu = new ServletFileUpload();
    String characterEncoding = request.getCharacterEncoding();
    if (characterEncoding == null) {
        characterEncoding = "UTF-8";
    }/*from  ww w  . j  a va  2  s  . c o  m*/
    sfu.setHeaderEncoding(characterEncoding);
    FileItemIterator iter = sfu.getItemIterator(request);

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream, characterEncoding));
        } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(stream, os);
                final byte[] bs = os.toByteArray();
                stream.close();

                listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                        new Class[] { FileItemStream.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if ("openStream".equals(method.getName())) {
                                    return new ByteArrayInputStream(bs);
                                }

                                return method.invoke(item, args);
                            }
                        }));
            }
        }
    }

    request.setAttribute(FileItemStream.class.getName(), listFiles);

    Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
                    // we replace getParameter() and getParameterValues()
                    // methods
                    if ("getParameter".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];
                        return requestParams.get(paramName);
                    }

                    if ("getParameterValues".equals(arg1.getName())) {
                        String paramName = (String) arg2[0];

                        // normalize name 'key[]' to 'key'
                        if (paramName.endsWith("[]"))
                            paramName = paramName.substring(0, paramName.length() - 2);

                        if (requestParams.containsKey(paramName))
                            return new String[] { requestParams.get(paramName) };

                        // if contains key[1], key[2]...
                        int i = 0;
                        List<String> paramValues = new ArrayList<String>();
                        while (true) {
                            String name2 = String.format("%s[%d]", paramName, i++);
                            if (requestParams.containsKey(name2)) {
                                paramValues.add(requestParams.get(name2));
                            } else {
                                break;
                            }
                        }

                        return paramValues.isEmpty() ? new String[0]
                                : paramValues.toArray(new String[paramValues.size()]);
                    }

                    return arg1.invoke(request, arg2);
                }
            });
    return (HttpServletRequest) proxyInstance;
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.HtmlReportOutput.java

/** 
 * @see com.jaspersoft.jasperserver.api.engine.scheduling.quartz.Output#getOutput()
 *//*  ww  w. j  a  va  2s. c o  m*/
public ReportOutput getOutput(EngineService engineService, ExecutionContext executionContext,
        String reportUnitURI, DataContainer htmlData, JRHyperlinkProducerFactory hyperlinkProducerFactory,
        RepositoryService repositoryService, JasperPrint jasperPrint, String baseFilename, Locale locale,
        String characterEncoding) throws JobExecutionException {
    try {
        String filename = baseFilename + ".html";
        String childrenFolderName = null;

        if (repositoryService != null)
            childrenFolderName = repositoryService.getChildrenFolderName(filename);
        else
            childrenFolderName = "";
        AbstractHtmlExporter exporter = null;

        if (isForceToUseHTMLExporter()) {
            // enforce to use grid-base exporter (only use for embedded report in email)
            exporter = new HtmlExporter();
        } else {
            exporter = HtmlExportUtil.getHtmlExporter(getJasperReportsContext());
        }
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, characterEncoding);

        HttpServletRequest proxy = (HttpServletRequest) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                new Class<?>[] { HttpServletRequest.class }, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        if ("getContextPath".equals(method.getName())) {
                            result = deploymentInformation.getDeploymentURI();
                        }
                        return result;
                    }
                });
        exporter.setParameter(new JRHtmlExporterParameter("HttpServletRequest"), proxy);

        boolean close = true;
        OutputStream htmlDataOut = htmlData.getOutputStream();

        try {
            ReportOutput htmlOutput = new ReportOutput(htmlData, ContentResource.TYPE_HTML, filename);

            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, htmlDataOut);
            if (!childrenFolderName.equals("")) {
                exporter.setImageHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "/{0}"));
                exporter.setResourceHandler(new RepoHtmlResourceHandler(htmlOutput, null));
                exporter.setFontHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "/{0}"));
            } else {
                exporter.setImageHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "{0}"));
                exporter.setResourceHandler(new RepoHtmlResourceHandler(htmlOutput, null));
                exporter.setFontHandler(new RepoHtmlResourceHandler(htmlOutput, childrenFolderName + "{0}"));
            }
            if (hyperlinkProducerFactory != null) {
                exporter.setParameter(JRExporterParameter.HYPERLINK_PRODUCER_FACTORY, hyperlinkProducerFactory);
            }

            exporter.exportReport();

            close = false;
            htmlDataOut.close();

            return htmlOutput;
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    htmlDataOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }
    } catch (JRException e) {
        throw new JSExceptionWrapper(e);
    }
}