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:grails.plugin.springsecurity.web.access.GrailsWebInvocationPrivilegeEvaluator.java

static HttpServletResponse createInstance() {
    return (HttpServletResponse) Proxy.newProxyInstance(HttpServletResponse.class.getClassLoader(),
            new Class[] { HttpServletResponse.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {
                    throw new UnsupportedOperationException();
                }//from   w  ww .  j av  a2 s  .c  o  m
            });
}

From source file:org.bsc.maven.plugin.confluence.PegdownParse.java

Visitor newVisitor(final int start_indent) {
    final ClassLoader cl = PegdownParse.class.getClassLoader();

    final InvocationHandler handler = new InvocationHandler() {

        int indent;
        {//from w  w w  .  j  a v a2  s  . c o  m
            this.indent = start_indent;
        }

        protected void visitChildren(Object proxy, Node node) {
            for (Node child : node.getChildren()) {
                child.accept((Visitor) proxy);
            }
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            for (int i = 0; i < indent; ++i)
                System.out.print('\t');
            final Object n = args[0];

            System.out.printf("[%s]", n);
            IfContext.iF(n, StrongEmphSuperNode.class, sesn).elseIf(n, ExpLinkNode.class, eln)
                    .elseIf(n, AnchorLinkNode.class, aln).elseIf(n, VerbatimNode.class, vln)
                    .elseIf(n, RefLinkNode.class, rln)

            ;
            System.out.println();

            if (n instanceof Node) {
                ++indent;
                visitChildren(proxy, (Node) args[0]);
                --indent;
            }
            return null;
        }

    };

    final Visitor proxy = (Visitor) Proxy.newProxyInstance(cl, new Class[] { Visitor.class }, handler);

    return proxy;

}

From source file:org.apache.camel.component.gae.http.GHttpEndpoint.java

/**
 * Proxies the {@link HttpBinding} returned by {@link super#getBinding()}
 * with a dynamic proxy. The proxy's invocation handler further delegates to
 * {@link InboundBinding#readRequest(org.apache.camel.Endpoint, Exchange, Object)}
 * ./*w  w w.  j a  v  a2s  .c  o  m*/
 * 
 * @return proxied {@link HttpBinding}.
 */
@Override
public HttpBinding getBinding() {
    return (HttpBinding) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { HttpBinding.class },
            new HttpBindingInvocationHandler<GHttpEndpoint, HttpServletRequest, HttpServletResponse>(this,
                    super.getBinding(), getInboundBinding()));
}

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

private Object getSingleton(final Method method) throws IllegalArgumentException {
    final Class<?> typeRef = method.getReturnType();
    final Singleton singleton = method.getAnnotation(Singleton.class);

    final URI uri = buildEntitySetURI(singleton.name(), service).build();
    final EntityUUID uuid = new EntityUUID(uri, typeRef);
    LOG.debug("Ask for singleton '{}'", typeRef.getSimpleName());

    EntityInvocationHandler handler = getContext().entityContext().getEntity(uuid);

    if (handler == null) {
        final ClientEntity entity = getClient().getObjectFactory().newEntity(new FullQualifiedName(
                typeRef.getAnnotation(Namespace.class).value(), ClassUtils.getEntityTypeName(typeRef)));

        handler = EntityInvocationHandler.getInstance(entity, uri, uri, typeRef, service);
    } else if (isDeleted(handler)) {
        // object deleted
        LOG.debug("Singleton '{}' has been deleted", typeRef.getSimpleName());
        handler = null;//from w  ww  .j a v a  2  s  . com
    }

    return handler == null ? null
            : Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { typeRef },
                    handler);
}

From source file:org.apache.olingo.ext.proxy.AbstractService.java

/**
 * Return an initialized concrete implementation of the passed EntityContainer interface.
 *
 * @param <T> interface annotated as EntityContainer
 * @param reference class object of the EntityContainer annotated interface
 * @return an initialized concrete implementation of the passed reference
 * @throws IllegalArgumentException if the passed reference is not an interface annotated as EntityContainer
 *//*from   www  .jav  a 2 s  . com*/
public <T> T getEntityContainer(final Class<T> reference)
        throws IllegalStateException, IllegalArgumentException {
    if (!ENTITY_CONTAINERS.containsKey(reference)) {
        final Object entityContainer = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { reference }, EntityContainerInvocationHandler.getInstance(reference, this));
        ENTITY_CONTAINERS.put(reference, entityContainer);
    }
    return reference.cast(ENTITY_CONTAINERS.get(reference));
}

From source file:org.apache.servicemix.camel.nmr.AttachmentTest.java

private <T> T createPort(QName serviceName, QName portName, Class<T> serviceEndpointInterface,
        boolean enableMTOM) throws Exception {
    Bus bus = BusFactory.getDefaultBus();
    ReflectionServiceFactoryBean serviceFactory = new JaxWsServiceFactoryBean();
    serviceFactory.setBus(bus);//from  w w w  .j a  va 2  s  .c  o m
    serviceFactory.setServiceName(serviceName);
    serviceFactory.setServiceClass(serviceEndpointInterface);
    serviceFactory.setWsdlURL(getClass().getResource("/wsdl/mtom_xop.wsdl"));
    Service service = serviceFactory.create();
    EndpointInfo ei = service.getEndpointInfo(portName);
    JaxWsEndpointImpl jaxwsEndpoint = new JaxWsEndpointImpl(bus, service, ei);
    SOAPBinding jaxWsSoapBinding = new SOAPBindingImpl(ei.getBinding());
    jaxWsSoapBinding.setMTOMEnabled(enableMTOM);

    Client client = new ClientImpl(bus, jaxwsEndpoint);
    InvocationHandler ih = new JaxWsClientProxy(client, jaxwsEndpoint.getJaxwsBinding());
    Object obj = Proxy.newProxyInstance(serviceEndpointInterface.getClassLoader(),
            new Class[] { serviceEndpointInterface, BindingProvider.class }, ih);
    return serviceEndpointInterface.cast(obj);
}

From source file:org.eclipse.wb.internal.xwt.parser.XwtRenderer.java

/**
 * Renders current content of {@link EditorContext} and fill objects for {@link XmlObjectInfo}s.
 *///  w  ww . j  a  va2 s .  c  o m
public void render() throws Exception {
    GlobalStateXml.activate(m_rootModel);
    // path -> model
    m_rootModel.accept(new ObjectInfoVisitor() {
        @Override
        public void endVisit(ObjectInfo objectInfo) throws Exception {
            if (objectInfo instanceof XmlObjectInfo) {
                XmlObjectInfo xmlObjectInfo = (XmlObjectInfo) objectInfo;
                CreationSupport creationSupport = xmlObjectInfo.getCreationSupport();
                if (!XmlObjectUtils.isImplicit(xmlObjectInfo)) {
                    DocumentElement element = creationSupport.getElement();
                    String path = XwtParser.getPath(element);
                    m_pathToModelMap.put(path, xmlObjectInfo);
                }
            }
        }
    });
    m_context.getBroadcastSupport().addListener(null, m_broadcast_setObjectAfter);
    // prepare IXWTLoader with intercepting IMetaclass loading 
    IXWTLoader loader;
    {
        final IXWTLoader loader0 = XWTLoaderManager.getActive();
        loader = (IXWTLoader) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class<?>[] { IXWTLoader.class }, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = method.invoke(loader0, args);
                        String methodSignature = ReflectionUtils.getMethodSignature(method);
                        if (methodSignature.equals("registerMetaclass(java.lang.Class)")
                                || methodSignature.equals("getMetaclass(java.lang.String,java.lang.String)")) {
                            IMetaclass metaclass = (IMetaclass) result;
                            hookProperties(metaclass);
                            hookProperties_ofExposedWidgets(metaclass);
                        }
                        return result;
                    }

                    private void hookProperties_ofExposedWidgets(IMetaclass metaclass) throws Exception {
                        for (Method typeMethod : metaclass.getType().getMethods()) {
                            Class<?> returnType = typeMethod.getReturnType();
                            if (typeMethod.getParameterTypes().length == 0
                                    && Widget.class.isAssignableFrom(returnType)) {
                                metaclass = (IMetaclass) ReflectionUtils.invokeMethod(loader0,
                                        "registerMetaclass(java.lang.Class)", returnType);
                                hookProperties(metaclass);
                            }
                        }
                    }
                });
    }
    // provide ResourceLoader with "postCreation"
    Core profile = new Core(new IElementLoaderFactory() {
        private int m_level;

        public IVisualElementLoader createElementLoader(IRenderingContext context, IXWTLoader loader) {
            return new ResourceLoader(context, loader) {
                @Override
                protected Integer getStyleValue(Element element, int styles) {
                    Integer styleValue = super.getStyleValue(element, styles);
                    if (styleValue != null) {
                        String path = XwtParser.getPath(element);
                        XmlObjectInfo xmlObject = m_pathToModelMap.get(path);
                        if (xmlObject != null) {
                            xmlObject.registerAttributeValue("x:Style", styleValue);
                        }
                    }
                    return styleValue;
                }

                @Override
                protected void postCreation0(final Element element, final Object targetObject) {
                    if (m_level > 1) {
                        return;
                    }
                    ExecutionUtils.runRethrow(new RunnableEx() {
                        public void run() throws Exception {
                            postCreationEx(element, targetObject);
                        }
                    });
                }

                private void postCreationEx(Element element, Object targetObject) throws Exception {
                    String path = XwtParser.getPath(element);
                    XmlObjectInfo xmlObjectInfo = m_pathToModelMap.get(path);
                    if (xmlObjectInfo == null) {
                        return;
                    }
                    // wrapper Shell, ignore it
                    {
                        Class<? extends Object> targetClass = targetObject.getClass();
                        if (targetClass != xmlObjectInfo.getDescription().getComponentClass()) {
                            if (targetClass == Shell.class) {
                                return;
                            }
                        }
                    }
                    // set Object
                    xmlObjectInfo.setObject(targetObject);
                }

                ////////////////////////////////////////////////////////////////////////////
                //
                // Tweaks for handling tested XWT files
                //
                ////////////////////////////////////////////////////////////////////////////
                private final Set<Element> m_processedElements = Sets.newHashSet();

                private boolean isRoot(Element element) {
                    if (!m_processedElements.contains(element)) {
                        m_processedElements.add(element);
                        String path = element.getPath();
                        return "0".equals(path);
                    }
                    return false;
                }

                @Override
                protected Object doCreate(Object parent, Element element, Class<?> constraintType,
                        Map<String, Object> options) throws Exception {
                    boolean isRoot = isRoot(element);
                    try {
                        if (isRoot) {
                            m_level++;
                        }
                        return super.doCreate(parent, element, constraintType, options);
                    } finally {
                        if (isRoot) {
                            m_level--;
                        }
                    }
                }
            };
        }
    }, loader);
    // render
    XWT.applyProfile(profile);
    ILoadingContext _loadingContext = XWT.getLoadingContext();
    XWT.setLoadingContext(new DefaultLoadingContext(m_context.getClassLoader()));
    try {
        URL url = m_context.getFile().getLocationURI().toURL();
        String content = m_context.getContent();
        Map<String, Object> options = Maps.newHashMap();
        options.put(IXWTLoader.DESIGN_MODE_PROPERTY, Boolean.TRUE);
        content = removeCompositeClassAttribute(content);
        XwtParser.configureForForms(m_context, options);
        XWT.loadWithOptions(IOUtils.toInputStream(content), url, options);
    } finally {
        XWT.setLoadingContext(_loadingContext);
        XWT.restoreProfile();
    }
}

From source file:ca.uhn.fhir.rest.client.RestfulClientFactory.java

@SuppressWarnings("unchecked")
private <T extends IRestfulClient> T instantiateProxy(Class<T> theClientType,
        InvocationHandler theInvocationHandler) {
    T proxy = (T) Proxy.newProxyInstance(theClientType.getClassLoader(), new Class[] { theClientType },
            theInvocationHandler);//from  w  w  w .  j  av a 2 s  .  co m
    return proxy;
}

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

@Override
@SuppressWarnings("unchecked")
public <S extends T> S getByKey(final KEY key, final Class<S> typeRef) throws IllegalArgumentException {
    if (key == null) {
        throw new IllegalArgumentException("Null key");
    }//from w w w.  j a va  2  s.  co m

    final EntityUUID uuid = new EntityUUID(this.baseURI, typeRef, key);
    LOG.debug("Ask for '{}({})'", typeRef.getSimpleName(), key);

    EntityInvocationHandler handler = getContext().entityContext().getEntity(uuid);

    if (handler == null) {
        final ClientEntity entity = getClient().getObjectFactory().newEntity(new FullQualifiedName(
                typeRef.getAnnotation(Namespace.class).value(), ClassUtils.getEntityTypeName(typeRef)));

        handler = EntityInvocationHandler.getInstance(key, entity, this.baseURI, typeRef, service);
    }

    if (isDeleted(handler)) {
        // object deleted
        LOG.debug("Object '{}({})' has been deleted", typeRef.getSimpleName(), uuid);
        return null;
    } else {
        // clear query options
        handler.clearQueryOptions();
        return (S) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { typeRef }, handler);
    }
}

From source file:org.kuali.kfs.module.tem.service.impl.CsvRecordFactory.java

public <RecordType> RecordType newInstance(final Map<String, List<Integer>> header, final String[] record)
        throws Exception {
    return (RecordType) Proxy.newProxyInstance(recordType.getClassLoader(), new Class[] { recordType },
            new CsvRecordInvocationHandler(header, record));
}