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:com.caucho.hessian.client.HessianProxy.java

/**
 * Handles the object invocation.//from   w w w. j  a va  2 s .c o  m
 * 
 * @param proxy
 *            the proxy object to invoke
 * @param method
 *            the method to call
 * @param args
 *            the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String mangleName;

    synchronized (_mangleMap) {
        mangleName = _mangleMap.get(method);
    }

    if (mangleName == null) {
        String methodName = method.getName();
        Class<?>[] params = method.getParameterTypes();
        // equals and hashCode are special cased
        if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
            Object value = args[0];
            if (value == null || !Proxy.isProxyClass(value.getClass()))
                return Boolean.FALSE;

            Object proxyHandler = Proxy.getInvocationHandler(value);

            if (!(proxyHandler instanceof HessianProxy))
                return Boolean.FALSE;

            HessianProxy handler = (HessianProxy) proxyHandler;

            return new Boolean(_url.equals(handler.getURL()));
        } else if (methodName.equals("hashCode") && params.length == 0)
            return new Integer(_url.hashCode());
        else if (methodName.equals("getHessianType"))
            return proxy.getClass().getInterfaces()[0].getName();
        else if (methodName.equals("getHessianURL"))
            return _url.toString();
        else if (methodName.equals("toString") && params.length == 0)
            return "HessianProxy[" + _url + "]";

        if (!_factory.isOverloadEnabled())
            mangleName = method.getName();
        else
            mangleName = mangleName(method);

        synchronized (_mangleMap) {
            _mangleMap.put(method, mangleName);
        }
    }
    InputStream is = null;
    HessianConnection conn = null;

    try {
        if (log.isLoggable(Level.FINER))
            log.finer("Hessian[" + _url + "] calling " + mangleName);
        conn = sendRequest(mangleName, args);

        if (conn.getStatusCode() != 200) {
            throw new HessianProtocolException("http code is " + conn.getStatusCode());
        }

        is = conn.getInputStream();

        if (log.isLoggable(Level.FINEST)) {
            PrintWriter dbg = new PrintWriter(new LogWriter(log));
            HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);

            dIs.startTop2();

            is = dIs;
        }

        AbstractHessianInput in;

        int code = is.read();

        if (code == 'H') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessian2Input(is);

            Object value = in.readReply(method.getReturnType());

            return value;
        } else if (code == 'r') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessianInput(is);

            in.startReplyBody();

            Object value = in.readObject(method.getReturnType());

            if (value instanceof InputStream) {
                value = new ResultInputStream(conn, is, in, (InputStream) value);
                is = null;
                conn = null;
            } else
                in.completeReply();

            return value;
        } else
            throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
    } catch (HessianProtocolException e) {
        throw new HessianRuntimeException(e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }

        try {
            if (conn != null)
                conn.destroy();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }
    }
}

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

public ControlLevel currentControlLevel(final DataModel datamodel) {

    final BeanDataModelInvocationHandler handler = (BeanDataModelInvocationHandler) Proxy
            .getInvocationHandler(datamodel);

    return ((BeanDataModelInvocationHandler.DataModelBeanContextSupport) handler.context).getControlLevel();
}

From source file:com.thinkbiganalytics.alerts.rest.AlertsModel.java

public com.thinkbiganalytics.alerts.rest.model.Alert toModel(com.thinkbiganalytics.alerts.api.Alert alert) {
    com.thinkbiganalytics.alerts.api.Alert baseAlert = alert;
    try {/*from www.j a  va 2  s  . c o  m*/
        if (Proxy.isProxyClass(alert.getClass())) {
            SourceAlert sourceAlert = (SourceAlert) Proxy.getInvocationHandler(alert);
            if (sourceAlert != null) {
                baseAlert = sourceAlert.getWrappedAlert();
            }
        }
    } catch (Exception e) {
        //unable to get base alert from proxy.  log the exception but continue
        log.error("Unable to get base alert from wrapped proxy for : {}, {} ", alert, e.getMessage(), e);

    }
    com.thinkbiganalytics.alerts.rest.model.Alert result = new com.thinkbiganalytics.alerts.rest.model.Alert();
    result.setId(alert.getId().toString());
    result.setActionable(alert.isActionable());
    result.setCreatedTime(alert.getCreatedTime());
    result.setLevel(toModel(alert.getLevel()));
    result.setState(toModel(alert.getState()));
    result.setType(alert.getType());
    result.setDescription(alert.getDescription());
    result.setCleared(alert.isCleared());
    result.setContent(alert.getContent() != null ? alert.getContent().toString() : null);
    result.setSubtype(alert.getSubtype());
    alert.getEvents().forEach(e -> result.getEvents().add(toModel(e)));
    if (baseAlert instanceof EntityAlert) {
        result.setEntityId(((EntityAlert) baseAlert).getEntityId() != null
                ? ((EntityAlert) baseAlert).getEntityId().toString()
                : null);
        result.setEntityType(((EntityAlert) baseAlert).getEntityType());
    }
    return result;
}

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

/**
 * actual method which is invoked once the lazy entity is about to be filled with life
 *///from  ww  w.j  a v a  2  s . c  om
private void lazyLoad() {
    if (lazy) {
        data = ((EntityInvocationHandler) Proxy.getInvocationHandler(find(collection, data.get(ID)))).data;
        lazy = false;
    }
}

From source file:com.wills.clientproxy.HessianLBProxy.java

/**
 * Handles the object invocation./*from   w w w .  jav  a2  s.  c o m*/
 * 
 * @param proxy
 *            the proxy object to invoke
 * @param method
 *            the method to call
 * @param args
 *            the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String mangleName;

    HessianClusterNode hcn = _cm.getAvailableNodeByStraitegy();
    if (hcn == null) {
        throw new Exception("no available server node found!");
    }
    if (hcn == null || hcn.getNode() == null) {
        throw new Exception("no server available");
    }

    threadLocal.set(new URL(hcn.getURL() + this._type.getSimpleName()));

    try {
        lock.readLock().lock();
        mangleName = _mangleMap.get(method);
    } finally {
        lock.readLock().unlock();
    }

    if (mangleName == null) {
        String methodName = method.getName();
        Class<?>[] params = method.getParameterTypes();
        // equals and hashCode are special cased
        if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
            Object value = args[0];
            if (value == null || !Proxy.isProxyClass(value.getClass()))
                return Boolean.FALSE;

            Object proxyHandler = Proxy.getInvocationHandler(value);

            if (!(proxyHandler instanceof HessianLBProxy))
                return Boolean.FALSE;

            HessianLBProxy handler = (HessianLBProxy) proxyHandler;

            return new Boolean(false);
        } else if (methodName.equals("hashCode") && params.length == 0)
            return new Integer(_cm.hashCode());
        else if (methodName.equals("getHessianType"))
            return proxy.getClass().getInterfaces()[0].getName();
        else if (methodName.equals("getHessianURL"))
            return threadLocal.get().toString();
        else if (methodName.equals("toString") && params.length == 0)
            return "HessianProxy[" + threadLocal.get() + "]";

        if (!_factory.isOverloadEnabled())
            mangleName = method.getName();
        else
            mangleName = mangleName(method);

        try {
            lock.writeLock().lock();
            _mangleMap.put(method, mangleName);
        } finally {
            lock.writeLock().unlock();
        }
    }
    InputStream is = null;
    HessianConnection conn = null;

    try {
        if (log.isLoggable(Level.FINER))
            log.finer("Hessian[" + threadLocal.get() + "] calling " + mangleName);
        conn = sendRequest(mangleName, args, threadLocal.get());

        if (conn.getStatusCode() != 200) {
            throw new HessianProtocolException("http code is " + conn.getStatusCode());
        }

        is = conn.getInputStream();

        if (log.isLoggable(Level.FINEST)) {
            PrintWriter dbg = new PrintWriter(new LogWriter(log));
            HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);

            dIs.startTop2();

            is = dIs;
        }

        AbstractHessianInput in;

        int code = is.read();

        if (code == 'H') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessian2Input(is);

            Object value = in.readReply(method.getReturnType());

            return value;
        } else if (code == 'r') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessianInput(is);

            in.startReplyBody();

            Object value = in.readObject(method.getReturnType());

            if (value instanceof InputStream) {
                value = new ResultInputStream(conn, is, in, (InputStream) value);
                is = null;
                conn = null;
            } else
                in.completeReply();

            return value;
        } else
            throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
    } catch (HessianProtocolException e) {
        throw new HessianRuntimeException(e);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }

        try {
            if (conn != null)
                conn.destroy();
        } catch (Exception e) {
            log.log(Level.FINE, e.toString(), e);
        }
    }
}

From source file:com.palantir.paxos.PaxosConsensusFastTest.java

@Test
public void learnerRecovery() {
    for (int i = 0; i < NUM_POTENTIAL_LEADERS * 3; i++) {
        state.gainLeadership(i % NUM_POTENTIAL_LEADERS);
    }//from   ww w. j a va2 s .  co m
    PaxosLearnerImpl learner = (PaxosLearnerImpl) ((DelegatingInvocationHandler) Proxy
            .getInvocationHandler(state.learner(0))).getDelegate();
    PaxosStateLog<PaxosValue> log = learner.log;
    SortedMap<Long, PaxosValue> cache = learner.state;
    log.truncate(log.getGreatestLogEntry());
    cache.clear();
    state.gainLeadership(0);
}

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

/** Stop this proxy. */
public void stopProxy(Object proxy) {
    try {//from   w w w  .  j a v a 2 s  .c  o  m
        ((Invoker) Proxy.getInvocationHandler(proxy)).close();
    } catch (IOException e) {
        LOG.warn("Error while stopping " + proxy, e);
    }
}

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

/**
 * simple test to make sure that the {@link MockBuilderFactory} can function in a minimal
 * way as an interceptor./*from w ww.j  av  a2 s .  c o  m*/
 */
@Test
@SuppressWarnings("unchecked")
public void testAsInterceptorFactory() {
    Log log = LogFactory.getLog(this.getClass());
    MockBuilderFactoryImpl factory = new MockBuilderFactoryImpl(false);
    factory.setLog(log);
    ServicesSetterImpl servicesSetter = new ServicesSetterImpl();
    factory.setServicesSetter(servicesSetter);
    factory.setBuilderFactory(createMock(ServiceImplementationFactory.class));
    // TODO have way to get testing logger.
    ServicePoint servicePoint = getServicePoint();
    final Class dependentServiceClass = ServiceImplementationFactory.class;
    List parameters = createMock(List.class);
    Module invokingModule = getModule(dependentServiceClass);
    servicesSetter.setModule(invokingModule);
    servicesSetter.setLog(log);
    ServicePoint someServicePoint = createMock(ServicePoint.class);
    expect(invokingModule.getServicePoint("someService")).andReturn(someServicePoint);
    replay(invokingModule, someServicePoint);

    List factoryParametersList = new ArrayList();
    List fakeParameter = createMock(List.class);
    replay(fakeParameter);
    // add something to the list that will complain if used.
    factoryParametersList.add(fakeParameter);
    ServiceImplementationFactoryParameters factoryParameters = createMock(
            ServiceImplementationFactoryParameters.class);
    expect(factoryParameters.getInvokingModule()).andReturn(invokingModule).anyTimes();
    expect(factoryParameters.getFirstParameter()).andReturn(factoryParametersList.get(0)).anyTimes();
    expect(factoryParameters.getParameters()).andReturn(factoryParametersList).anyTimes();
    expect(factoryParameters.getServiceInterface()).andReturn(SomeService.class).anyTimes();
    expect(factoryParameters.getServiceId()).andReturn("someService");
    replay(factoryParameters);
    ServiceImplementationFactory rootService = createMock(ServiceImplementationFactory.class);
    final SomeService realCreatedService = createMock(SomeService.class);
    expect(rootService.createCoreServiceImplementation(isA(ServiceImplementationFactoryParameters.class)))
            .andAnswer(new IAnswer<Object>() {

                public Object answer() throws Throwable {
                    ServiceImplementationFactoryParameters object = (ServiceImplementationFactoryParameters) getCurrentArguments()[0];

                    // make sure being passed the proxy
                    assertTrue(Proxy.isProxyClass(object.getInvokingModule().getClass()),
                            "Did not get passed a module proxy");
                    assertTrue(object.getInvokingModule().containsService(dependentServiceClass),
                            dependentServiceClass + ": module does not have service with this interface");
                    //        TODO            List dependentService = (List) object.getInvokingModule().getService(dependentServiceClass);
                    return realCreatedService;
                }

            });
    replay(rootService, realCreatedService);

    InterceptorStack stack = new InterceptorStackImpl(log, servicePoint, rootService);

    // create the interceptor
    factory.createInterceptor(stack, invokingModule, parameters);
    ServiceImplementationFactory intercepted = (ServiceImplementationFactory) stack.peek();

    assertNotNull(intercepted);

    SomeService result = (SomeService) intercepted.createCoreServiceImplementation(factoryParameters);
    MockSwitcher switcher = (MockSwitcher) Proxy.getInvocationHandler(result);
    assertSame(switcher.getRealService(), realCreatedService);
    assertSame(switcher.getUnderlyingService(), realCreatedService);

    // now tell factory that we always want the mock.
    factory.getMockOverride().add(SomeService.class);
    assertSame(switcher.getRealService(), realCreatedService);
    assertNotSame(switcher.getUnderlyingService(), realCreatedService);
}

From source file:com.msopentech.odatajclient.proxy.api.impl.SequentialContainer.java

private int processEntityContext(EntityTypeInvocationHandler handler, int pos, TransactionItems items,
        List<EntityLinkDesc> delayedUpdates) {
    LOG.debug("Process '{}'", handler);
    items.put(handler, null);//from w ww  .j a  v a 2 s  .c o m

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

    final AttachedEntityStatus currentStatus = EntityContainerFactory.getContext().entityContext()
            .getStatus(handler);

    if (AttachedEntityStatus.DELETED != currentStatus) {
        entity.getProperties().clear();
        EngineUtils.addProperties(client, factory.getMetadata(), handler.getPropertyChanges(), entity);
    }

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

        final Set<EntityTypeInvocationHandler> toBeLinked = new HashSet<EntityTypeInvocationHandler>();
        final String serviceRoot = factory.getServiceRoot();

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

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

            final AttachedEntityStatus status;

            try {
                status = EntityContainerFactory.getContext().entityContext().getStatus(target);
            } catch (IllegalStateException e) {
                // this case takes place if we iterate through collection and current item does not have any changes
                // TODO find another way to look for changes in collection
                continue;
            }

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

            if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
                    && !target.isChanged()) {
                entity.addLink(buildNavigationLink(property.getKey().name(),
                        URIUtils.getURI(serviceRoot, editLink.toASCIIString()), type));
            } else {
                if (!items.contains(target)) {
                    pos = processEntityContext(target, pos, items, delayedUpdates);
                    pos++;
                }

                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) {
                    entity.addLink(buildNavigationLink(property.getKey().name(),
                            URIUtils.getURI(serviceRoot, 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));
        }
    }

    // commit to server
    LOG.debug("{}: Send '{}' to service", pos, handler);
    send(handler, entity);

    items.put(handler, pos);
    int startingPos = pos;

    if (handler.getEntity().isMediaEntity()) {

        // update media properties
        if (!handler.getPropertyChanges().isEmpty()) {
            final URI targetURI = currentStatus == AttachedEntityStatus.NEW ? URI.create("$" + startingPos)
                    : URIUtils.getURI(factory.getServiceRoot(),
                            handler.getEntity().getEditLink().toASCIIString());
            update(handler, targetURI, entity);
            pos++;
            items.put(handler, pos);
        }

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

            updateMediaEntity(handler, targetURI, handler.getStreamChanges());

            // update media info (use null key)
            pos++;
            items.put(null, pos);
        }
    }

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

        updateMediaResource(handler, targetURI, streamedChanges.getValue());

        // update media info (use null key)
        pos++;
        items.put(handler, pos);
    }

    return pos;
}

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

@Override
public boolean add(final T element) {
    if (element instanceof Proxy && Proxy.getInvocationHandler(element) instanceof EntityInvocationHandler) {
        final EntityInvocationHandler handler = EntityInvocationHandler.class
                .cast(Proxy.getInvocationHandler(element));
        if (!service.getContext().entityContext().isAttached(handler) && baseURI != null) {
            handler.updateUUID(baseURI, itemRef, null);
            service.getContext().entityContext().attachNew(handler);
        }/*from  www . j a v  a2s .c om*/
    }
    return items.add(element);
}