List of usage examples for java.lang.reflect Proxy isProxyClass
public static boolean isProxyClass(Class<?> cl)
From source file:org.openengsb.core.persistence.internal.SerializableChecker.java
private void internalCheck(Object obj) { if (obj == null) { return;/*from w w w .jav a 2s . c om*/ } Class<?> cls = obj.getClass(); nameStack.add(simpleName); traceStack.add(new TraceSlot(obj, fieldDescription)); if (!(obj instanceof Serializable) && (!Proxy.isProxyClass(cls))) { throw new ObjectDbNotSerializableException(toPrettyPrintedStack(obj.getClass().getName()), exception); } ObjectStreamClass desc; for (;;) { try { desc = (ObjectStreamClass) lookupMethod.invoke(null, cls, Boolean.TRUE); obj = invokeWriteReplaceMethod.invoke(desc, obj); Class<?> repCl = obj.getClass(); if (!(Boolean) hasWriteReplaceMethodMetod.invoke(desc, (Object[]) null) || obj == null || repCl == cls) { break; } cls = repCl; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } if (cls.isPrimitive()) { LOGGER.trace("skip primitive check"); } else if (cls.isArray()) { checked.put(obj, null); Class<?> ccl = cls.getComponentType(); if (!(ccl.isPrimitive())) { Object[] objs = (Object[]) obj; for (int i = 0; i < objs.length; i++) { String arrayPos = "[" + i + "]"; simpleName = arrayPos; fieldDescription += arrayPos; check(objs[i]); } } } else if (obj instanceof Externalizable && (!Proxy.isProxyClass(cls))) { Externalizable extObj = (Externalizable) obj; try { extObj.writeExternal(new ObjectOutputAdaptor() { private int count = 0; @Override public void writeObject(Object streamObj) throws IOException { if (checked.containsKey(streamObj)) { return; } checked.put(streamObj, null); String arrayPos = "[write:" + count++ + "]"; simpleName = arrayPos; fieldDescription += arrayPos; check(streamObj); } }); } catch (Exception e) { if (e instanceof ObjectDbNotSerializableException) { throw (ObjectDbNotSerializableException) e; } LOGGER.warn("error delegating to Externalizable : " + e.getMessage() + ", path: " + currentPath()); } } else { Method writeObjectMethod = null; if (!writeObjectMethodMissing.contains(cls)) { try { writeObjectMethod = cls.getDeclaredMethod("writeObject", new Class[] { java.io.ObjectOutputStream.class }); } catch (SecurityException e) { writeObjectMethodMissing.add(cls); } catch (NoSuchMethodException e) { writeObjectMethodMissing.add(cls); } } final Object original = obj; if (writeObjectMethod != null) { class InterceptingObjectOutputStream extends ObjectOutputStream { private int counter; InterceptingObjectOutputStream() throws IOException { super(DUMMY_OUTPUT_STREAM); enableReplaceObject(true); } @Override protected Object replaceObject(Object streamObj) throws IOException { if (streamObj == original) { return streamObj; } counter++; if (checked.containsKey(streamObj)) { return null; } checked.put(streamObj, null); String arrayPos = "[write:" + counter + "]"; simpleName = arrayPos; fieldDescription += arrayPos; check(streamObj); return streamObj; } } InterceptingObjectOutputStream ioos = null; try { ioos = new InterceptingObjectOutputStream(); ioos.writeObject(obj); } catch (Exception e) { if (e instanceof ObjectDbNotSerializableException) { throw (ObjectDbNotSerializableException) e; } LOGGER.warn("error delegating to writeObject : " + e.getMessage() + ", path: " + currentPath()); } finally { IOUtils.closeQuietly(ioos); } } else { Object[] slots; try { slots = (Object[]) getClassDataLayoutMethod.invoke(desc, (Object[]) null); } catch (Exception e) { throw new RuntimeException(e); } for (Object slot : slots) { ObjectStreamClass slotDesc; try { Field descField = slot.getClass().getDeclaredField("desc"); descField.setAccessible(true); slotDesc = (ObjectStreamClass) descField.get(slot); } catch (Exception e) { throw new RuntimeException(e); } checked.put(obj, null); checkFields(obj, slotDesc); } } } traceStack.removeLast(); nameStack.removeLast(); }
From source file:com.github.cherimojava.data.mongo.entity.EntityInvocationHandler.java
/** * equals method of the entity represented by this EntityInvocationHandler instance. Objects are considered unequal * (false) if o is://from w w w .ja v a 2 s .com * <ul> * <li>null * <li>no Proxy * <li>different Proxy class * <li>Different Entity class * <li>Data doesn't match * </ul> * If all the above is false both entities are considered equal and true will be returned * * @param o object to compare this instance with * @return true if both objects match the before mentioned criteria otherwise false */ private boolean _equals(Object o) { if (o == null) { return false; } if (!Proxy.isProxyClass(o.getClass())) { // for all non proxies we know that we can return false return false; } InvocationHandler ihandler = Proxy.getInvocationHandler(o); if (!ihandler.getClass().equals(getClass())) { // for all proxies not being EntityInvocationHandler return false return false; } EntityInvocationHandler handler = (EntityInvocationHandler) ihandler; if (!handler.properties.getEntityClass().equals(properties.getEntityClass())) { // this is not the same entity class, so false return false; } // make sure both have all lazy dependencies resolved lazyLoad(); handler.lazyLoad(); return data.equals(handler.data); }
From source file:io.coala.json.DynaBean.java
/** * @param <T>/*from w w w . j a v a 2s .c o m*/ * @param wrapperType * @return */ static final <T> JsonSerializer<T> createJsonSerializer(final Class<T> type) { return new JsonSerializer<T>() { @Override public void serialize(final T value, final JsonGenerator jgen, final SerializerProvider serializers) throws IOException, JsonProcessingException { // non-Proxy objects get default treatment if (!Proxy.isProxyClass(value.getClass())) { @SuppressWarnings("unchecked") final JsonSerializer<T> ser = (JsonSerializer<T>) serializers .findValueSerializer(value.getClass()); if (ser != this) ser.serialize(value, jgen, serializers); else LOG.warn("Problem serializing: {}", value); return; } // BeanWrapper gets special treatment if (DynaBeanInvocationHandler.class.isInstance(Proxy.getInvocationHandler(value))) { final DynaBeanInvocationHandler handler = (DynaBeanInvocationHandler) Proxy .getInvocationHandler(value); // Wrapper extensions get special treatment if (Wrapper.class.isAssignableFrom(handler.type)) { final Object wrap = handler.bean.get("wrap"); serializers.findValueSerializer(wrap.getClass(), null).serialize(wrap, jgen, serializers); return; } // Config (Accessible) extensions get special treatment else if (Accessible.class.isAssignableFrom(handler.type)) { final Map<String, Object> copy = new HashMap<>(handler.bean.any()); final Accessible config = (Accessible) handler.config; for (String key : config.propertyNames()) copy.put(key, config.getProperty(key)); serializers.findValueSerializer(copy.getClass(), null).serialize(copy, jgen, serializers); return; } else if (Config.class.isAssignableFrom(handler.type)) throw new JsonGenerationException("BeanWrapper should extend " + Accessible.class.getName() + " required for serialization: " + Arrays.asList(handler.type.getInterfaces()), jgen); // BeanWrappers that do not extend OWNER API's Config serializers.findValueSerializer(handler.bean.getClass(), null).serialize(handler.bean, jgen, serializers); return; } // Config (Accessible) gets special treatment if (Accessible.class.isInstance(value)) { final Accessible config = (Accessible) value; final Properties entries = new Properties(); for (String key : config.propertyNames()) entries.put(key, config.getProperty(key)); serializers.findValueSerializer(entries.getClass(), null).serialize(entries, jgen, serializers); return; } if (Config.class.isInstance(value)) throw new JsonGenerationException("Config should extend " + Accessible.class.getName() + " required for serialization: " + Arrays.asList(value.getClass().getInterfaces()), jgen); throw new JsonGenerationException( "No serializer found for proxy of: " + Arrays.asList(value.getClass().getInterfaces()), jgen); } }; }
From source file:net.paoding.rose.web.impl.module.ModulesBuilderImpl.java
private boolean checkController(final XmlWebApplicationContext context, String beanName, ModuleImpl module) throws IllegalAccessException { AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) context.getBeanFactory() .getBeanDefinition(beanName); String beanClassName = beanDefinition.getBeanClassName(); String controllerSuffix = null; for (String suffix : RoseConstants.CONTROLLER_SUFFIXES) { if (beanClassName.length() > suffix.length() && beanClassName.endsWith(suffix)) { if (suffix.length() == 1 && Character .isUpperCase(beanClassName.charAt(beanClassName.length() - suffix.length() - 1))) { continue; }//w ww .j a v a 2 s .c om controllerSuffix = suffix; break; } } if (controllerSuffix == null) { if (beanDefinition.hasBeanClass()) { Class<?> beanClass = beanDefinition.getBeanClass(); if (beanClass.isAnnotationPresent(Path.class)) { throw new IllegalArgumentException( "@" + Path.class.getSimpleName() + " is only allowed in Resource/Controller, " + "is it a Resource/Controller? wrong spelling? : " + beanClassName); } } // ?l?r?uer?or??? if (beanClassName.endsWith("Controler") || beanClassName.endsWith("Controllor") || beanClassName.endsWith("Resouce") || beanClassName.endsWith("Resorce")) { // ?throw??? logger.error("", new IllegalArgumentException( "invalid class name end wrong spelling? : " + beanClassName)); } return false; } String[] controllerPaths = null; if (!beanDefinition.hasBeanClass()) { try { beanDefinition.resolveBeanClass(Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new CannotLoadBeanClassException("", beanName, beanDefinition.getBeanClassName(), e); } } final Class<?> clazz = beanDefinition.getBeanClass(); final String controllerName = StringUtils.removeEnd(ClassUtils.getShortNameAsProperty(clazz), controllerSuffix); Path reqMappingAnnotation = clazz.getAnnotation(Path.class); if (reqMappingAnnotation != null) { controllerPaths = reqMappingAnnotation.value(); } if (controllerPaths != null) { // controllerPaths.length==0path?controller for (int i = 0; i < controllerPaths.length; i++) { if ("#".equals(controllerPaths[i])) { controllerPaths[i] = "/" + controllerName; } else if (controllerPaths[i].equals("/")) { controllerPaths[i] = ""; } else if (controllerPaths[i].length() > 0 && controllerPaths[i].charAt(0) != '/') { controllerPaths[i] = "/" + controllerPaths[i]; } if (controllerPaths[i].length() > 1 && controllerPaths[i].endsWith("/")) { if (controllerPaths[i].endsWith("//")) { throw new IllegalArgumentException("invalid path '" + controllerPaths[i] + "' for controller " + beanClassName + ": don't end with more than one '/'"); } controllerPaths[i] = controllerPaths[i].substring(0, controllerPaths[i].length() - 1); } } } else { // TODO: ?0.91.0?201007?? if (controllerName.equals("index") || controllerName.equals("home") || controllerName.equals("welcome")) { // ??IndexController/HomeController/WelcomeController@Path("") throw new IllegalArgumentException("please add @Path(\"\") to " + clazz.getName()); } else { controllerPaths = new String[] { "/" + controllerName }; } } // Controller??Context?? // Context??? Object controller = context.getBean(beanName); module.addController(// controllerPaths, clazz, controllerName, controller); if (Proxy.isProxyClass(controller.getClass())) { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': add controller " + Arrays.toString(controllerPaths) + "= proxy of " + clazz.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() // + "': add controller " + Arrays.toString(controllerPaths) + "= " + controller.getClass().getName()); } } return true; }
From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java
private boolean checkController(final XmlWebApplicationContext context, String beanName, ModuleImpl module) throws IllegalAccessException { AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) context.getBeanFactory() .getBeanDefinition(beanName); String beanClassName = beanDefinition.getBeanClassName(); String controllerSuffix = null; for (String suffix : BlitzConstants.CONTROLLER_SUFFIXES) { if (beanClassName.length() > suffix.length() && beanClassName.endsWith(suffix)) { if (suffix.length() == 1 && Character .isUpperCase(beanClassName.charAt(beanClassName.length() - suffix.length() - 1))) { continue; }//from w w w .ja v a 2 s . c o m controllerSuffix = suffix; break; } } if (controllerSuffix == null) { if (beanDefinition.hasBeanClass()) { Class<?> beanClass = beanDefinition.getBeanClass(); if (beanClass.isAnnotationPresent(Path.class)) { throw new IllegalArgumentException( "@" + Path.class.getSimpleName() + " is only allowed in Resource/Controller, " + "is it a Resource/Controller? wrong spelling? : " + beanClassName); } } // ?l?r?uer?or??? if (beanClassName.endsWith("Controler") || beanClassName.endsWith("Controllor") || beanClassName.endsWith("Resouce") || beanClassName.endsWith("Resorce")) { // ?throw??? logger.error("", new IllegalArgumentException( "invalid class name end wrong spelling? : " + beanClassName)); } return false; } String[] controllerPaths = null; if (!beanDefinition.hasBeanClass()) { try { beanDefinition.resolveBeanClass(Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new CannotLoadBeanClassException("", beanName, beanDefinition.getBeanClassName(), e); } } final Class<?> clazz = beanDefinition.getBeanClass(); final String controllerName = StringUtils.removeEnd(ClassUtils.getShortNameAsProperty(clazz), controllerSuffix); Path reqMappingAnnotation = clazz.getAnnotation(Path.class); if (reqMappingAnnotation != null) { controllerPaths = reqMappingAnnotation.value(); } if (controllerPaths != null) { // controllerPaths.length==0path?controller for (int i = 0; i < controllerPaths.length; i++) { if ("#".equals(controllerPaths[i])) { controllerPaths[i] = "/" + controllerName; } else if (controllerPaths[i].equals("/")) { controllerPaths[i] = ""; } else if (controllerPaths[i].length() > 0 && controllerPaths[i].charAt(0) != '/') { controllerPaths[i] = "/" + controllerPaths[i]; } if (controllerPaths[i].length() > 1 && controllerPaths[i].endsWith("/")) { if (controllerPaths[i].endsWith("//")) { throw new IllegalArgumentException("invalid path '" + controllerPaths[i] + "' for controller " + beanClassName + ": don't end with more than one '/'"); } controllerPaths[i] = controllerPaths[i].substring(0, controllerPaths[i].length() - 1); } } } else { // TODO: ?0.91.0?201007?? if (controllerName.equals("index") || controllerName.equals("home") || controllerName.equals("welcome")) { // ??IndexController/HomeController/WelcomeController@Path("") throw new IllegalArgumentException("please add @Path(\"\") to " + clazz.getName()); } else { controllerPaths = new String[] { "/" + controllerName }; } } // Controller??Context?? // Context??? Object controller = context.getBean(beanName); module.addController(// controllerPaths, clazz, controllerName, controller); if (Proxy.isProxyClass(controller.getClass())) { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': add controller " + Arrays.toString(controllerPaths) + "= proxy of " + clazz.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() // + "': add controller " + Arrays.toString(controllerPaths) + "= " + controller.getClass().getName()); } } return true; }
From source file:com.sinosoft.one.mvc.web.impl.module.ModulesBuilderImpl.java
private boolean checkController(final XmlWebApplicationContext context, String beanName, ModuleImpl module) throws IllegalAccessException { AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) context.getBeanFactory() .getBeanDefinition(beanName); String beanClassName = beanDefinition.getBeanClassName(); String controllerSuffix = null; for (String suffix : MvcConstants.CONTROLLER_SUFFIXES) { if (beanClassName.length() > suffix.length() && beanClassName.endsWith(suffix)) { if (suffix.length() == 1 && Character .isUpperCase(beanClassName.charAt(beanClassName.length() - suffix.length() - 1))) { continue; }//from w w w . j a v a 2 s .c o m controllerSuffix = suffix; break; } } if (controllerSuffix == null) { if (beanDefinition.hasBeanClass()) { Class<?> beanClass = beanDefinition.getBeanClass(); if (beanClass.isAnnotationPresent(Path.class)) { throw new IllegalArgumentException( "@" + Path.class.getSimpleName() + " is only allowed in Resource/Controller, " + "is it a Resource/Controller? wrong spelling? : " + beanClassName); } } // ?l?r?uer?or??? if (beanClassName.endsWith("Controler") || beanClassName.endsWith("Controllor") || beanClassName.endsWith("Resouce") || beanClassName.endsWith("Resorce")) { // ?throw??? logger.error("", new IllegalArgumentException( "invalid class name end wrong spelling? : " + beanClassName)); } return false; } String[] controllerPaths = null; if (!beanDefinition.hasBeanClass()) { try { beanDefinition.resolveBeanClass(Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new CannotLoadBeanClassException("", beanName, beanDefinition.getBeanClassName(), e); } } final Class<?> clazz = beanDefinition.getBeanClass(); final String controllerName = StringUtils.removeEnd(ClassUtils.getShortNameAsProperty(clazz), controllerSuffix); Path reqMappingAnnotation = clazz.getAnnotation(Path.class); if (reqMappingAnnotation != null) { controllerPaths = reqMappingAnnotation.value(); } if (controllerPaths != null) { // controllerPaths.length==0path?controller for (int i = 0; i < controllerPaths.length; i++) { if ("#".equals(controllerPaths[i])) { controllerPaths[i] = "/" + controllerName; } else if (controllerPaths[i].equals("/")) { controllerPaths[i] = ""; } else if (controllerPaths[i].length() > 0 && controllerPaths[i].charAt(0) != '/') { controllerPaths[i] = "/" + controllerPaths[i]; } if (controllerPaths[i].length() > 1 && controllerPaths[i].endsWith("/")) { if (controllerPaths[i].endsWith("//")) { throw new IllegalArgumentException("invalid path '" + controllerPaths[i] + "' for controller " + beanClassName + ": don't end with more than one '/'"); } controllerPaths[i] = controllerPaths[i].substring(0, controllerPaths[i].length() - 1); } } } else { // TODO: ?0.91.0?201007?? if (controllerName.equals("index") || controllerName.equals("home") || controllerName.equals("welcome")) { // ??IndexController/HomeController/WelcomeController@Path("") throw new IllegalArgumentException("please add @Path(\"\") to " + clazz.getName()); } else { controllerPaths = new String[] { "/" + controllerName }; } } // Controller??Context?? // Context??? Object controller = context.getBean(beanName); module.addController(// controllerPaths, clazz, controllerName, controller); if (Proxy.isProxyClass(controller.getClass())) { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() + "': add controller " + Arrays.toString(controllerPaths) + "= proxy of " + clazz.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("module '" + module.getMappingPath() // + "': add controller " + Arrays.toString(controllerPaths) + "= " + controller.getClass().getName()); } } return true; }
From source file:com.jeeframework.util.classes.ClassUtils.java
/** * Return a descriptive name for the given object's type: usually simply * the class name, but component type class name + "[]" for arrays, * and an appended list of implemented interfaces for JDK proxies. * @param value the value to introspect/*from w ww . jav a 2 s. c o m*/ * @return the qualified name of the class */ public static String getDescriptiveType(Object value) { if (value == null) { return null; } Class clazz = value.getClass(); if (Proxy.isProxyClass(clazz)) { StringBuffer buf = new StringBuffer(clazz.getName()); buf.append(" implementing "); Class[] ifcs = clazz.getInterfaces(); for (int i = 0; i < ifcs.length; i++) { buf.append(ifcs[i].getName()); if (i < ifcs.length - 1) { buf.append(','); } } return buf.toString(); } else if (clazz.isArray()) { return getQualifiedNameForArray(clazz); } else { return clazz.getName(); } }
From source file:org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.java
/** * Delegate an incoming invocation from the proxy, dispatching to EntityManagerFactoryInfo * or the native EntityManagerFactory accordingly. *///from w ww . j a v a 2 s.c om Object invokeProxyMethod(Method method, @Nullable Object[] args) throws Throwable { if (method.getDeclaringClass().isAssignableFrom(EntityManagerFactoryInfo.class)) { return method.invoke(this, args); } else if (method.getName().equals("createEntityManager") && args != null && args.length > 0 && args[0] == SynchronizationType.SYNCHRONIZED) { // JPA 2.1's createEntityManager(SynchronizationType, Map) // Redirect to plain createEntityManager and add synchronization semantics through Spring proxy EntityManager rawEntityManager = (args.length > 1 ? getNativeEntityManagerFactory().createEntityManager((Map<?, ?>) args[1]) : getNativeEntityManagerFactory().createEntityManager()); return ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, true); } // Look for Query arguments, primarily JPA 2.1's addNamedQuery(String, Query) if (args != null) { for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg instanceof Query && Proxy.isProxyClass(arg.getClass())) { // Assumably a Spring-generated proxy from SharedEntityManagerCreator: // since we're passing it back to the native EntityManagerFactory, // let's unwrap it to the original Query object from the provider. try { args[i] = ((Query) arg).unwrap(null); } catch (RuntimeException ex) { // Ignore - simply proceed with given Query object then } } } } // Standard delegation to the native factory, just post-processing EntityManager return values Object retVal = method.invoke(getNativeEntityManagerFactory(), args); if (retVal instanceof EntityManager) { // Any other createEntityManager variant - expecting non-synchronized semantics EntityManager rawEntityManager = (EntityManager) retVal; retVal = ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, false); } return retVal; }
From source file:com.dianping.resource.io.util.ClassUtils.java
/** * Return a descriptive name for the given object's type: usually simply * the class name, but component type class name + "[]" for arrays, * and an appended list of implemented interfaces for JDK proxies. * @param value the value to introspect//from w w w . j a v a 2 s .c o m * @return the qualified name of the class */ public static String getDescriptiveType(Object value) { if (value == null) { return null; } Class<?> clazz = value.getClass(); if (Proxy.isProxyClass(clazz)) { StringBuilder result = new StringBuilder(clazz.getName()); result.append(" implementing "); Class<?>[] ifcs = clazz.getInterfaces(); for (int i = 0; i < ifcs.length; i++) { result.append(ifcs[i].getName()); if (i < ifcs.length - 1) { result.append(','); } } return result.toString(); } else if (clazz.isArray()) { return getQualifiedNameForArray(clazz); } else { return clazz.getName(); } }
From source file:com.freetmp.common.util.ClassUtils.java
public static String getDescriptiveType(Object value) { if (value == null) { return null; }/*from ww w . j a v a 2 s .com*/ Class<?> clazz = value.getClass(); if (Proxy.isProxyClass(clazz)) { StringBuilder result = new StringBuilder(clazz.getName()); result.append(" implementing "); Class<?>[] ifcs = clazz.getInterfaces(); for (int i = 0; i < ifcs.length; i++) { result.append(ifcs[i].getName()); if (i < ifcs.length - 1) { result.append(','); } } return result.toString(); } else if (clazz.isArray()) { return getQualifiedNameForArray(clazz); } else { return clazz.getName(); } }