Example usage for java.lang.reflect Proxy getInvocationHandler

List of usage examples for java.lang.reflect Proxy getInvocationHandler

Introduction

In this page you can find the example usage for java.lang.reflect Proxy getInvocationHandler.

Prototype

@CallerSensitive
public static InvocationHandler getInvocationHandler(Object proxy) throws IllegalArgumentException 

Source Link

Document

Returns the invocation handler for the specified proxy instance.

Usage

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

protected int processEntityContext(final EntityInvocationHandler handler, int pos, final TransactionItems items,
        final List<EntityLinkDesc> delayedUpdates, final PersistenceChanges changeset) {
    int posNumber = pos;
    items.put(handler, null);/*from  w w  w  .j a v  a  2 s . c o m*/

    final ClientEntity entity = handler.getEntity();
    entity.getNavigationLinks().clear();

    final AttachedEntityStatus currentStatus = service.getContext().entityContext().getStatus(handler);
    LOG.debug("Process '{}({})'", handler, currentStatus);

    if (AttachedEntityStatus.DELETED != currentStatus) {
        entity.getProperties().clear();
        CoreUtils.addProperties(service.getClient(), handler.getPropertyChanges(), entity);

        entity.getAnnotations().clear();
        CoreUtils.addAnnotations(service.getClient(), handler.getAnnotations(), entity);

        for (Map.Entry<String, AnnotatableInvocationHandler> entry : handler.getPropAnnotatableHandlers()
                .entrySet()) {
            CoreUtils.addAnnotations(service.getClient(), entry.getValue().getAnnotations(),
                    entity.getProperty(entry.getKey()));
        }
    }

    for (Map.Entry<NavigationProperty, Object> property : handler.getLinkChanges().entrySet()) {
        final ClientLinkType type = Collection.class.isAssignableFrom(property.getValue().getClass())
                ? ClientLinkType.ENTITY_SET_NAVIGATION
                : ClientLinkType.ENTITY_NAVIGATION;

        final Set<EntityInvocationHandler> toBeLinked = new HashSet<EntityInvocationHandler>();

        for (Object proxy : type == ClientLinkType.ENTITY_SET_NAVIGATION ? (Collection<?>) property.getValue()
                : Collections.singleton(property.getValue())) {

            final EntityInvocationHandler target = (EntityInvocationHandler) Proxy.getInvocationHandler(proxy);

            final AttachedEntityStatus status;
            if (!service.getContext().entityContext().isAttached(target)) {
                status = resolveNavigationLink(property.getKey(), target);
            } else {
                status = service.getContext().entityContext().getStatus(target);
            }

            LOG.debug("Found link to '{}({})'", target, status);

            final URI editLink = target.getEntity().getEditLink();

            if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
                    && !target.isChanged()) {
                LOG.debug("Add link to '{}'", target);
                entity.addLink(buildNavigationLink(property.getKey().name(),
                        URIUtils.getURI(service.getClient().getServiceRoot(), editLink.toASCIIString()), type));
            } else {
                if (!items.contains(target)) {
                    posNumber = processEntityContext(target, posNumber, items, delayedUpdates, changeset);
                    posNumber++;
                }

                final Integer targetPos = items.get(target);
                if (targetPos == null) {
                    // schedule update for the current object
                    LOG.debug("Schedule '{}' from '{}' to '{}'", type.name(), handler, target);
                    toBeLinked.add(target);
                } else if (status == AttachedEntityStatus.CHANGED) {
                    LOG.debug("Changed: '{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);
                    entity.addLink(buildNavigationLink(property.getKey().name(),
                            URIUtils.getURI(service.getClient().getServiceRoot(), editLink.toASCIIString()),
                            type));
                } else {
                    // create the link for the current object
                    LOG.debug("'{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);

                    entity.addLink(
                            buildNavigationLink(property.getKey().name(), URI.create("$" + targetPos), type));
                }
            }
        }

        if (!toBeLinked.isEmpty()) {
            delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, toBeLinked, type));
        }

        if (property.getValue() instanceof Proxy) {
            final InvocationHandler target = Proxy.getInvocationHandler(property.getValue());

            if (target instanceof EntityCollectionInvocationHandler) {
                for (String ref : ((EntityCollectionInvocationHandler<?>) target).referenceItems) {
                    delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, ref));
                }
            }
        }
    }

    for (Map.Entry<String, AnnotatableInvocationHandler> entry : handler.getNavPropAnnotatableHandlers()
            .entrySet()) {

        CoreUtils.addAnnotations(service.getClient(), entry.getValue().getAnnotations(),
                entity.getNavigationLink(entry.getKey()));
    }

    final AttachedEntityStatus processedStatus = queue(handler, entity, changeset);
    if (processedStatus != null) {
        // insert into the process queue
        LOG.debug("{}: Insert '{}' into the process queue", posNumber, handler);
        items.put(handler, posNumber);
    } else {
        posNumber--;
    }

    if (processedStatus != AttachedEntityStatus.DELETED) {
        int startingPos = posNumber;

        if (handler.getEntity().isMediaEntity() && handler.isChanged()) {
            // update media properties
            if (!handler.getPropertyChanges().isEmpty()) {
                final URI targetURI = currentStatus == AttachedEntityStatus.NEW ? URI.create("$" + startingPos)
                        : URIUtils.getURI(service.getClient().getServiceRoot(),
                                handler.getEntity().getEditLink().toASCIIString());
                queueUpdate(handler, targetURI, entity, changeset);
                posNumber++;
                items.put(handler, posNumber);
                LOG.debug("{}: Update media properties for '{}' into the process queue", posNumber, handler);
            }

            // update media content
            if (handler.getStreamChanges() != null) {
                final URI targetURI = currentStatus == AttachedEntityStatus.NEW
                        ? URI.create("$" + startingPos + "/$value")
                        : URIUtils.getURI(service.getClient().getServiceRoot(),
                                handler.getEntity().getEditLink().toASCIIString() + "/$value");

                queueUpdateMediaEntity(handler, targetURI, handler.getStreamChanges(), changeset);

                // update media info (use null key)
                posNumber++;
                items.put(null, posNumber);
                LOG.debug("{}: Update media info for '{}' into the process queue", posNumber, handler);
            }
        }

        for (Map.Entry<String, EdmStreamValue> streamedChanges : handler.getStreamedPropertyChanges()
                .entrySet()) {
            final URI targetURI = currentStatus == AttachedEntityStatus.NEW ? URI.create("$" + startingPos)
                    : URIUtils.getURI(service.getClient().getServiceRoot(),
                            CoreUtils.getMediaEditLink(streamedChanges.getKey(), entity).toASCIIString());

            queueUpdateMediaResource(handler, targetURI, streamedChanges.getValue(), changeset);

            // update media info (use null key)
            posNumber++;
            items.put(handler, posNumber);
            LOG.debug("{}: Update media info (null key) for '{}' into the process queue", posNumber, handler);
        }
    }

    return posNumber;
}

From source file:com.amazonaws.hal.client.HalResourceInvocationHandler.java

/**
 *///from w  w  w .j  a  v  a  2 s  .c om
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (halResource == null || !halResource.isDefined()) {
        halResource = halClient.getHalResource(resourcePath);
    }

    try {
        Method resourceInfoMethod = ResourceInfo.class.getMethod(method.getName(), method.getParameterTypes());

        return resourceInfoMethod.invoke(halResource, args);
    } catch (NoSuchMethodException ignore) {
        // If the method is not defined in ResourceInfo, we handle it below
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }

    Link link;
    if ((link = method.getAnnotation(Link.class)) != null) {
        switch (link.method()) {
        case GET:
            if (List.class.isAssignableFrom(method.getReturnType())) {
                //noinspection unchecked
                return new HalLinkList(halResource, link.relation(),
                        (Class) getCollectionType(method.getGenericReturnType(), 0, ResourceInfo.class),
                        halClient);
            } else if (Map.class.isAssignableFrom(method.getReturnType())) {
                //noinspection unchecked
                return new HalLinkMap(halResource, link.relation(), link.keyField(),
                        (Class) getCollectionType(method.getGenericReturnType(), 1, ResourceInfo.class),
                        halClient);
            } else {
                return halClient.getResource(halResource, method.getReturnType(), getRelationHref(link,
                        args == null ? EMPTY_ARGS : args, method.getParameterAnnotations()), false);
            }

        case POST:
            if (args == null) {
                throw new IllegalArgumentException("POST operations require a representation argument.");
            }

            return halClient.postResource(method.getReturnType(),
                    getRelationHref(link, args, method.getParameterAnnotations()), args[0]);

        case PUT:
            if (args == null) {
                throw new IllegalArgumentException("PUT operations require a representation argument.");
            }

            return halClient.putResource(method.getReturnType(),
                    getRelationHref(link, args, method.getParameterAnnotations()), args[0]);

        case DELETE:
            return halClient.deleteResource(method.getReturnType(),
                    getRelationHref(link, args == null ? EMPTY_ARGS : args, method.getParameterAnnotations()));

        default:
            throw new UnsupportedOperationException("Unexpected HTTP method: " + link.method());
        }

    } else if (method.getName().startsWith("get")) {
        String propertyName = getPropertyName(method.getName());
        Object property = halResource.getProperty(propertyName);
        Type returnType = method.getGenericReturnType();

        // When a value is accessed, it's intended type can either be a
        // class or some other type (like a ParameterizedType).
        //
        // If the target type is a class and the value is of that type,
        // we return it.  If the value is not of that type, we convert
        // it and store the converted value (trusting it was converted
        // properly) back to the backing store.
        //
        // If the target type is not a class, it may be ParameterizedType
        // like List<T> or Map<K, V>.  We check if the value is already
        // a converting type and if so, we return it.  If the value is
        // not, we convert it and if it's now a converting type, we store
        // the new value in the backing store.

        if (returnType instanceof Class) {
            if (!((Class) returnType).isInstance(property)) {
                property = convert(returnType, property);

                //noinspection unchecked
                halResource.addProperty(propertyName, property);
            }
        } else {
            if (!(property instanceof ConvertingMap) && !(property instanceof ConvertingList)) {
                property = convert(returnType, property);

                if (property instanceof ConvertingMap || property instanceof ConvertingList) {
                    //noinspection unchecked
                    halResource.addProperty(propertyName, property);
                }
            }
        }

        return property;
    } else if (method.getName().equals("toString") && args == null) {
        return resourcePath;
    } else if (method.getName().equals("equals") && args != null && args.length == 1) {
        HalResourceInvocationHandler other;

        try {
            other = (HalResourceInvocationHandler) Proxy.getInvocationHandler(args[0]);
        } catch (IllegalArgumentException e) {
            // argument is not a proxy
            return false;
        } catch (ClassCastException e) {
            // argument is the wrong type of proxy
            return false;
        }

        return resourcePath.equals(other.resourcePath);
    } else if (method.getName().equals("hashCode") && args == null) {
        return resourcePath.hashCode();
    }

    throw new UnsupportedOperationException("Don't know how to handle '" + method.getName() + "'");
}

From source file:org.apache.hadoop.hbase.ipc.WritableRpcEngine.java

/**
 * Stop this proxy and release its invoker's resource
 * @param proxy the proxy to be stopped//from www. j a v  a  2  s .c o  m
 */
public void stopProxy(VersionedProtocol proxy) {
    if (proxy != null) {
        ((Invoker) Proxy.getInvocationHandler(proxy)).close();
    }
}

From source file:gov.nih.nci.firebird.proxy.FaultTolerantProxyFactoryTest.java

private void verifyProxyChain(TestClientI wrappedClient) throws Exception {
    assertTrue(Proxy.isProxyClass(wrappedClient.getClass()));
    RetryHandler retryHandler = (RetryHandler) Proxy.getInvocationHandler(wrappedClient);
    Provider<TestClientI> provider = (Provider<TestClientI>) retryHandler.getClientProvider();

    TestClientI pooledClient = provider.get();
    assertTrue(Proxy.isProxyClass(pooledClient.getClass()));
    PoolingHandler poolingHandler = (PoolingHandler) Proxy.getInvocationHandler(pooledClient);
    ObjectPool<Object> pool = poolingHandler.getPool();
    TestClientI client = (TestClientI) pool.borrowObject();
    assertNotNull(client);/*from   w  w  w  .j  a  v  a  2s .  c o m*/

    assertTrue(retryHandler.getValidExceptions().containsAll(VALID_EXCEPTIONS));
    assertTrue(poolingHandler.getValidExceptions().containsAll(VALID_EXCEPTIONS));
}

From source file:org.springframework.aop.framework.OptimizedJdkDynamicAopProxy.java

/**
 * Equality means interceptors and interfaces and
 * TargetSource are equal./*from www . j a  v a2 s  .c  o m*/
 * @see java.lang.Object#equals(java.lang.Object)
 * @param other may be a dynamic proxy wrapping an instance
 * of this class
 */
public boolean equals(Object other) {
    if (other == null)
        return false;
    if (other == this)
        return true;

    OptimizedJdkDynamicAopProxy aopr2 = null;
    if (other instanceof OptimizedJdkDynamicAopProxy) {
        aopr2 = (OptimizedJdkDynamicAopProxy) other;
    } else if (Proxy.isProxyClass(other.getClass())) {
        InvocationHandler ih = Proxy.getInvocationHandler(other);
        if (!(ih instanceof OptimizedJdkDynamicAopProxy))
            return false;
        aopr2 = (OptimizedJdkDynamicAopProxy) ih;
    } else {
        // Not a valid comparison
        return false;
    }

    // If we get here, aopr2 is the other AopProxy
    return AopProxyUtils.equalsInProxy(this.advised, aopr2.advised);
}

From source file:no.sesat.search.datamodel.BeanDataNodeInvocationHandler.java

/**
 * obj may be null./*from  w  w  w.  j a  va 2 s. c  om*/
 */
@Override
protected void removeChild(final Object obj) {

    if (null != obj) {

        assert isDataObjectOrNode(obj) : "my own properties should only be Data(Object|Node)s";

        final BeanDataObjectInvocationHandler<?> childsOldHandler = (BeanDataObjectInvocationHandler<?>) Proxy
                .getInvocationHandler(obj);
        context.remove(childsOldHandler.getBeanContextChild());

    }
}

From source file:com.cy.dcts.identityVerify.service.impl.IdentityVerifyServiceImpl.java

private String executeClient(String serviceUrl, String license, String condition) throws MalformedURLException {
    ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
    Protocol protocol = new Protocol("https", easy, 443);
    Protocol.registerProtocol("https", protocol);

    Service serviceModel = new ObjectServiceFactory().create(NciisServices.class, "NciisServices", null, null);

    NciisServices service = (NciisServices) new XFireProxyFactory().create(serviceModel,
            serviceUrl + "NciicServices");

    Client client = ((XFireProxy) Proxy.getInvocationHandler(service)).getClient();
    client.addOutHandler(new DOMOutHandler());

    ///*from   ww w.  ja  v a  2s  .  c  om*/
    client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.TRUE);

    //
    client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
    client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");

    /**
     * ??
     */
    String licenseCode = null;
    String result = null;
    BufferedReader in;
    try {
        String filePath = ServletActionContext.getServletContext().getRealPath(license + ".txt");
        in = new BufferedReader(new FileReader(filePath));
        licenseCode = in.readLine();

        //
        result = service.nciicCheck(licenseCode, condition);

        //????
        //result = service.nciicGetCondition(licenseCode);

        in.close();//?
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    _log.info(result);
    return result;
}

From source file:ipc.WritableRpcEngine.java

/**
 * Stop this proxy and release its invoker's resource
 * @param proxy the proxy to be stopped//from   w  w w  .ja va 2 s .c om
 */
public void stopProxy(Object proxy) {
    ((Invoker) Proxy.getInvocationHandler(proxy)).close();
}

From source file:com.msopentech.odatajclient.proxy.EntityRetrieveTestITCase.java

@Test
public void checkForETag() {
    Product product = getContainer().getProduct().get(-10);
    assertTrue(StringUtils/*from  w w w .ja  v  a  2  s .c  o  m*/
            .isNotBlank(((EntityTypeInvocationHandler) Proxy.getInvocationHandler(product)).getETag()));
}

From source file:org.apache.olingo.fit.proxy.v3.EntityRetrieveTestITCase.java

@Test
public void checkForETag() {
    Product product = getContainer().getProduct().getByKey(-10).load();
    assertTrue(/* w  w w.jav a 2 s .c om*/
            StringUtils.isNotBlank(((EntityInvocationHandler) Proxy.getInvocationHandler(product)).getETag()));
}