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.kuali.kra.questionnaire.QuestionnaireLookupableHelperServiceTest.java

/**
 * //from  ww w. jav  a 2 s  .  c  o  m
 * This method to test getCustomActionUrls for someone with "VIEW_QUESTIONNAIRE" permission
 * should only have view action links
 * @throws Exception
 */
@Test
public void testCustomActionUrlWithMODIFY_QUESTIONNAIRE() throws Throwable {
    final QuestionnaireAuthorizationService questionnaireAuthorizationService = context
            .mock(QuestionnaireAuthorizationService.class);
    Method m = QuestionnaireLookupableHelperServiceImpl.class.getMethod("setQuestionnaireAuthorizationService",
            QuestionnaireAuthorizationService.class);
    Proxy.getInvocationHandler(questionnaireLookupableHelperServiceImpl).invoke(
            questionnaireLookupableHelperServiceImpl, m, new Object[] { questionnaireAuthorizationService });

    context.checking(new Expectations() {
        {
            one(questionnaireAuthorizationService).hasPermission(PermissionConstants.MODIFY_QUESTIONNAIRE);
            will(returnValue(true));
            one(questionnaireAuthorizationService).hasPermission(PermissionConstants.VIEW_QUESTIONNAIRE);
            will(returnValue(true));
        }
    });
    MaintenanceDocumentBase maintDocument = (MaintenanceDocumentBase) documentService
            .getNewDocument(KcServiceLocator.getService(MaintenanceDocumentDictionaryService.class)
                    .getDocumentTypeName(Questionnaire.class));
    maintDocument.getDocumentHeader().setDocumentDescription("test 1");
    maintDocument.getNewMaintainableObject().setBusinessObject(createQuestionnaire("test1", "desc 1"));
    maintDocument.getNewMaintainableObject().setMaintenanceAction(KRADConstants.MAINTENANCE_NEW_ACTION);
    documentService.routeDocument(maintDocument, null, null);
    // not sure why it is not persisted in DB.  also need to do this save, so getcustomactionurls can retrieve it with bos
    Questionnaire questionnaire = (Questionnaire) maintDocument.getNewMaintainableObject().getDataObject();
    questionnaire.setDocumentNumber(maintDocument.getDocumentNumber());
    KNSServiceLocator.getBusinessObjectService()
            .save((Questionnaire) maintDocument.getNewMaintainableObject().getDataObject());
    List pkNames = new ArrayList();
    pkNames.add("id");

    List<HtmlData> htmldata = questionnaireLookupableHelperServiceImpl
            .getCustomActionUrls(maintDocument.getNewMaintainableObject().getBusinessObject(), pkNames);
    Assert.assertEquals(4, htmldata.size());
    Assert.assertEquals(
            "../maintenanceQn.do?businessObjectClassName=" + Questionnaire.class.getName()
                    + "&methodToCall=edit" + "&id=" + questionnaire.getId(),
            ((AnchorHtmlData) htmldata.get(0)).getHref(), ((AnchorHtmlData) htmldata.get(0)).getHref());
    Assert.assertEquals(
            "../maintenanceQn.do?businessObjectClassName=" + Questionnaire.class.getName()
                    + "&methodToCall=edit" + "&id=" + questionnaire.getId() + "&readOnly=true",
            ((AnchorHtmlData) htmldata.get(1)).getHref(), ((AnchorHtmlData) htmldata.get(1)).getHref());
    Assert.assertEquals(
            "../maintenanceQn.do?businessObjectClassName=" + Questionnaire.class.getName()
                    + "&methodToCall=copy" + "&id=" + questionnaire.getId(),
            ((AnchorHtmlData) htmldata.get(2)).getHref(), ((AnchorHtmlData) htmldata.get(2)).getHref());
}

From source file:cat.albirar.framework.dynabean.impl.DynaBeanImpl.java

/**
 * Dynamically implemented {@link Object#equals(Object)} method.
 * /*w w  w .  j  a  v a  2s . com*/
 * @param oOrigin The 'other' object
 * @return as equals specification
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public boolean equals(Object oOrigin) {
    T theOther;
    DynaBeanImpl theOtherDynaBean = null;
    Object o;

    // Check if 'other' is a null
    if (oOrigin == null) {
        return false;
    }
    if (Proxy.isProxyClass(oOrigin.getClass())) {
        o = Proxy.getInvocationHandler(oOrigin);
    } else {
        o = oOrigin;
    }
    // Check for self-equals...
    if (o == this) {
        return true;
    }
    // Check if 'the other' is a 'implementedType' type...
    if (descriptor.getImplementedType().isAssignableFrom(o.getClass()) == false) {
        // ...if not, can be a dynaBean?...
        if (DynaBeanImpl.class.isAssignableFrom(o.getClass())) {
            theOtherDynaBean = (DynaBeanImpl) o;

            // Yes, check if the implementedType is the same or derived
            if (getImplementedType().isAssignableFrom(theOtherDynaBean.getImplementedType()) == false) {
                return false;
            }
        } else {
            // Is not implemented type nor ProxyBeanImpl...
            return false;
        }
    }
    theOther = (T) o;
    for (DynaBeanPropertyDescriptor property : descriptor.getProperties()) {
        try {
            Object value;
            if (theOtherDynaBean != null) {
                value = theOtherDynaBean.values.get(property.propertyName);
            } else {
                value = property.getterMethod.invoke(theOther);
            }

            if (ObjectUtils.nullSafeEquals(values.get(property.propertyName), value) == false) {
                return false;
            }
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException
                | InvocationTargetException e) {
            throw new RuntimeException("On equals call!", e);
        }
    }
    return true;
}

From source file:org.wrml.runtime.DefaultModel.java

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

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();

    final Model model = (Model) proxy;
    final String methodName = method.getName();

    final Class<?> modelClass = model.getClass();
    final Class<?>[] modelClassInterfaces = modelClass.getInterfaces();

    // Get the model class's first implemented interface; it's schema interface
    final Class<?> modelSchemaInterface = modelClassInterfaces[0];
    final URI modelSchemaUri = schemaLoader.getTypeUri(modelSchemaInterface);
    final Prototype prototype = schemaLoader.getPrototype(modelSchemaUri);

    // Get the class that defined the invoked method
    final Class<?> declaringClass = method.getDeclaringClass();

    //// www. j a va  2 s.  c  o  m
    // If the invoked method comes from one of the base model types, then it may need to be handled in a
    // special way.
    //

    if (declaringClass.equals(ValueType.JAVA_TYPE_MODEL) || declaringClass.equals(Object.class)
            || declaringClass.equals(Comparable.class)) {

        // The invoked method was declared by one of the base model types, it may be a special case method.
        final SpecialMethod specialMethod = SpecialMethod.fromString(methodName);

        if (specialMethod != null) {

            // LOG.debug("Model method: " + method + " is considered a special method.");

            // The name of the invoked method matches the name of one of our special cases.

            final int argCount = (args != null) ? args.length : 0;
            final boolean hasArgs = argCount > 0;
            final Object firstArg = (hasArgs) ? args[0] : null;

            switch (specialMethod) {

            // Handle the special case methods:

            case clearSlotValue: {

                if (argCount == 1 && firstArg instanceof String) {
                    final String slotName = (String) firstArg;
                    return clearSlotValue(model, slotName, modelSchemaUri);
                }

                break;
            }

            case containsSlotValue: {
                if (argCount == 1 && firstArg instanceof String) {
                    final String slotName = (String) firstArg;
                    return containsSlotValue(model, slotName, modelSchemaUri);
                }

                break;
            }

            case equals: {

                if (argCount == 1) {
                    final Object other = firstArg;
                    if (other instanceof Proxy) {
                        return equals(Proxy.getInvocationHandler(other));
                    }
                    return false;
                }

                break;
            }

            case getKeys: {
                if (argCount == 0) {

                    return buildKeys(model);
                }

                break;
            }

            case getPrototype: {
                if (argCount == 0) {

                    return prototype;
                }

                break;
            }

            case getSchemaUri: {
                if (argCount == 0) {

                    if (ValueType.JAVA_TYPE_MODEL.equals(modelSchemaInterface)) {
                        // Return null (undefined Schema) if we are only a Model
                        return null;
                    }

                    // Reflect back the WRML representation
                    return modelSchemaUri;
                }

                break;
            }

            case getSlotValue: {

                if (argCount >= 1) {
                    final String slotName = (String) firstArg;
                    final ProtoSlot protoSlot = prototype.getProtoSlot(slotName);
                    return getSlotValue(model, slotName, protoSlot.getDeclaringSchemaUri());
                }

                break;
            }
            case initKeySlots: {

                if (argCount == 1) {
                    final Keys keys = (Keys) firstArg;
                    initKeySlots(model, keys);
                    return null;
                }

                break;
            }
            case reference: {

                if (argCount >= 1) {

                    final String linkSlotName = (String) firstArg;
                    final LinkProtoSlot linkProtoSlot = prototype.getProtoSlot(linkSlotName);

                    Object[] referenceMethodArgs = null;
                    if (argCount > 1) {
                        referenceMethodArgs = ArrayUtils.subarray(args, 1, args.length);
                    }
                    return invokeReference(model, linkProtoSlot, referenceMethodArgs);

                }

                break;
            }

            case setSlotValue: {

                if (argCount >= 2) {
                    final String slotName = (String) firstArg;
                    final Object slotValue = args[1];
                    final ProtoSlot protoSlot = prototype.getProtoSlot(slotName);
                    return setSlotValue(model, slotName, slotValue, protoSlot.getDeclaringSchemaUri());
                }

                break;
            }
            default:
                break;

            } // End of switch

        }

        // LOG.debug("Model method: " + method + " was not handled as a special case.");

        // Proxy to this RuntimeModel itself, since it is all of the above
        // declaring classes (independent of Proxy's magic trick).
        return method.invoke(this, args);
    }

    final JavaBean schemaBean = prototype.getSchemaBean();
    final SortedMap<String, SortedSet<JavaMethod>> linkMethods = schemaBean.getOtherMethods();

    if (linkMethods.containsKey(methodName)) {
        String linkSlotName = methodName;

        if (linkSlotName.startsWith(JavaBean.GET)) {
            linkSlotName = methodName.substring(3);
            linkSlotName = Character.toLowerCase(linkSlotName.charAt(0)) + linkSlotName.substring(1);
        }

        final LinkProtoSlot linkProtoSlot = prototype.getProtoSlot(linkSlotName);

        DefaultModel.LOG.debug("Model method: " + method
                + " is considered a link/reference assicuated with slot: " + linkProtoSlot);

        // The java method's invocation is interpreted as a link reference (i.e. "click").
        return invokeReference(model, linkProtoSlot, args);
    }

    //
    // Determine if the method name looks like a slot accessor (setter/getter) meaning that it starts with "get",
    // "set", or "is".
    //

    boolean isWrite = false;
    String slotName = null;

    if (methodName.startsWith(JavaBean.GET)) {
        slotName = methodName.substring(3);
    } else if (methodName.startsWith(JavaBean.IS)) {
        slotName = methodName.substring(2);
    } else if (methodName.startsWith(JavaBean.SET)) {
        slotName = methodName.substring(3);
        isWrite = true;
    }

    if (slotName != null) {
        slotName = Character.toLowerCase(slotName.charAt(0)) + slotName.substring(1);

        final URI declaringSchemaUri = schemaLoader.getTypeUri(declaringClass);

        if (isWrite) {
            final Object newSlotValue = args[0];
            final Object oldSlotValue = setSlotValue(model, slotName, newSlotValue, declaringSchemaUri);
            return oldSlotValue;
        } else {
            final Object slotValue = getSlotValue(model, slotName, declaringSchemaUri);

            return slotValue;
        }
    }

    throw new ModelException("Model method invocation was not handled for method: " + method, null, model);
}

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

@Override
public void delete(final KEY key) throws IllegalArgumentException {
    final EntityContext entityContext = getContext().entityContext();

    EntityInvocationHandler entity = entityContext.getEntity(new EntityUUID(baseURI, itemRef, key));

    if (entity == null) {
        // search for entity
        final T searched = getByKey(key);
        entity = (EntityInvocationHandler) Proxy.getInvocationHandler(searched);
        entityContext.attach(entity, AttachedEntityStatus.DELETED);
    } else {/*from  w w w  . j  a  va  2  s. c  o m*/
        entityContext.setStatus(entity, AttachedEntityStatus.DELETED);
    }
}

From source file:fr.ign.cogit.geoxygene.datatools.ojb.GeOxygeneBrokerHelper.java

/**
 * returns an Array with an Objects PK VALUES if convertToSql is true, any
 * associated java-to-sql conversions are applied. If the Object is a Proxy or
 * a VirtualProxy NO conversion is necessary.
 * //from w ww  .  j a v  a  2 s.c  om
 * @param objectOrProxy
 * @param convertToSql
 * @return Object[]
 * @throws PersistenceBrokerException
 */
public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy, boolean convertToSql,
        Connection conn) throws PersistenceBrokerException {
    /*
     * arminw Check it out. Because the isProxyClass method is costly and most
     * objects aren't proxies, I add a instanceof check before. Is every Proxy a
     * instance of Proxy?
     */
    if ((objectOrProxy instanceof Proxy) && Proxy.isProxyClass(objectOrProxy.getClass())) {
        IndirectionHandler handler;
        handler = (IndirectionHandler) Proxy.getInvocationHandler(objectOrProxy);
        return this.getKeyValues(cld, handler.getIdentity(), convertToSql); // BRJ:
                                                                            // convert
                                                                            // Identity
    } else if (objectOrProxy instanceof VirtualProxy) {
        IndirectionHandler handler;
        handler = VirtualProxy.getIndirectionHandler((VirtualProxy) objectOrProxy);
        return this.getKeyValues(cld, handler.getIdentity(), convertToSql); // BRJ:
                                                                            // convert
                                                                            // Identity
    } else {
        ClassDescriptor realCld = this.getRealClassDescriptor(cld, objectOrProxy);
        return this.getValuesForObject(realCld.getPkFields(), objectOrProxy, convertToSql, conn);
    }
}

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

@Override
public <S extends T> void delete(final S entity) {
    deleteEntity((EntityInvocationHandler) Proxy.getInvocationHandler(entity), this.baseURI);
}

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

/**
 * Equality means interfaces, advisors and TargetSource are equal.
 * <p>The compared object may be a JdkDynamicAopProxy instance itself
 * or a dynamic proxy wrapping a JdkDynamicAopProxy instance.
 *///from  w ww  . ja va  2 s  .co m
@Override
public boolean equals(@Nullable Object other) {
    if (other == this) {
        return true;
    }
    if (other == null) {
        return false;
    }

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

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

From source file:com.mystudy.source.spring.aop.JdkDynamicAopProxy.java

/**
 * Equality means interfaces, advisors and TargetSource are equal.
 * <p>The compared object may be a JdkDynamicAopProxy instance itself
 * or a dynamic proxy wrapping a JdkDynamicAopProxy instance.
 *//* www  .j ava  2  s.  co m*/
@Override
public boolean equals(Object other) {
    if (other == this) {
        return true;
    }
    if (other == null) {
        return false;
    }

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

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

From source file:org.kuali.coeus.sys.impl.service.SpringBeanConfigurationTest.java

/**
 * This method looks for the same bean name in different context but of different class types.
 * This is either a "partial" bean override or a bean name conflict
 *//*  w  w w  .  j  a  v a  2s .c om*/
@Test
public void test_beans_across_other_contexts_name_conflict() {
    final HashMap<String, Set<Class<?>>> beans = new HashMap<>();
    toEachSpringBean(new VoidFunction() {
        @Override
        public void r(ApplicationContext context, String name) {
            Object o = context.getBean(name);
            if (o != null) {
                Set<Class<?>> beanClasses = beans.get(name);
                if (beanClasses == null) {
                    beanClasses = new HashSet<>();
                }

                final Class<?> clazz;
                if (Proxy.isProxyClass(o.getClass())) {
                    try {
                        clazz = (Class<?>) Proxy.getInvocationHandler(o).invoke(o,
                                Object.class.getMethod("getClass", new Class[] {}), new Object[] {});
                    } catch (Throwable e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    clazz = o.getClass();
                }

                beanClasses.add(clazz);
                beans.put(name, beanClasses);
            } else {
                LOG.warn("bean " + name + " is null");
            }

        }
    }, true);

    final Set<Map.Entry<String, Set<Class<?>>>> entrySet = new HashSet<>(beans.entrySet());
    CollectionUtils.filter(entrySet, new Predicate<Map.Entry<String, Set<Class<?>>>>() {
        @Override
        public boolean evaluate(Map.Entry<String, Set<Class<?>>> object) {
            return object.getValue().size() > 1;
        }
    });

    Assert.assertTrue(
            "The following bean names are duplicated in different contexts with different class names "
                    + entrySet,
            entrySet.isEmpty());
}

From source file:org.springmodules.xt.model.generator.factory.FactoryGeneratorInterceptor.java

private boolean doEquals(Object proxy, Object other) {
    if (other != null && Proxy.isProxyClass(other.getClass())) {
        return Proxy.getInvocationHandler(proxy) == Proxy.getInvocationHandler(other);
    } else {/*from   ww  w.jav a2 s  .co m*/
        return false;
    }
}