Example #1
1
  private Prop findRelProperty(Class<?> fromCls, String rel, Class<?> toCls) {
    Object entity = !fromCls.isInterface() ? data.constructor.create(fromCls) : null;

    for (Prop prop : Beany.propertiesOf(fromCls).select(data.relPropSelector)) {

      String relName = null;

      if (!fromCls.isInterface()) {
        Object value = prop.getRaw(entity);
        if (hasEntityLinks(value)) {
          EntityLinks links = entityLinks(value);
          relName = links.relationName();
        }
      } else {
        Rel relation = prop.getAnnotation(Rel.class);
        if (relation != null) {
          relName = relation.value();
        }
      }

      if (relName != null && relName.equals(rel)) {
        if (prop.getRawTypeArg(0).equals(toCls)) {
          return prop;
        }
      }
    }

    Log.warn(
        "Didn't find inverse relation property!", "relation", rel, "from", fromCls, "to", toCls);
    return null;
  }
Example #2
1
  /**
   * Returns the generic supertype for {@code supertype}. For example, given a class {@code
   * IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the
   * result when the supertype is {@code Collection.class} is {@code Collection<Integer>}.
   */
  static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
    if (toResolve == rawType) {
      return context;
    }

    // we skip searching through interfaces if unknown is an interface
    if (toResolve.isInterface()) {
      Class<?>[] interfaces = rawType.getInterfaces();
      for (int i = 0, length = interfaces.length; i < length; i++) {
        if (interfaces[i] == toResolve) {
          return rawType.getGenericInterfaces()[i];
        } else if (toResolve.isAssignableFrom(interfaces[i])) {
          return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
        }
      }
    }

    // check our supertypes
    if (!rawType.isInterface()) {
      while (rawType != Object.class) {
        Class<?> rawSupertype = rawType.getSuperclass();
        if (rawSupertype == toResolve) {
          return rawType.getGenericSuperclass();
        } else if (toResolve.isAssignableFrom(rawSupertype)) {
          return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
        }
        rawType = rawSupertype;
      }
    }

    // we can't resolve this further
    return toResolve;
  }
  private void configureMapperTypesIfPossible(Job j, Class<? extends Mapper> mapper) {
    // Find mapper
    Class<?> targetClass = mapper;
    Type targetType = mapper;

    do {
      targetType = targetClass.getGenericSuperclass();
      targetClass = targetClass.getSuperclass();
    } while (targetClass != null
        && targetClass != Object.class
        && !Mapper.class.equals(targetClass));

    if (targetType instanceof ParameterizedType) {
      Type[] params = ((ParameterizedType) targetType).getActualTypeArguments();
      if (params.length == 4) {
        // set each param (if possible);
        if (params[2] instanceof Class) {
          Class<?> clz = (Class<?>) params[2];
          if (!clz.isInterface()) j.setMapOutputKeyClass(clz);
        }

        // set each param (if possible);
        if (params[3] instanceof Class) {
          Class<?> clz = (Class<?>) params[3];
          if (!clz.isInterface()) {
            j.setMapOutputValueClass(clz);
          }
        }
      }
    }
  }
Example #4
1
  static JavaMembers lookupClass(
      Scriptable scope, Class<?> dynamicType, Class<?> staticType, boolean includeProtected) {
    JavaMembers members;
    ClassCache cache = ClassCache.get(scope);
    Map<Class<?>, JavaMembers> ct = cache.getClassCacheMap();

    Class<?> cl = dynamicType;
    for (; ; ) {
      members = ct.get(cl);
      if (members != null) {
        if (cl != dynamicType) {
          // member lookup for the original class failed because of
          // missing privileges, cache the result so we don't try
          // again
          ct.put(dynamicType, members);
        }
        return members;
      }
      try {
        members = new JavaMembers(cache.getAssociatedScope(), cl, includeProtected);
        break;
      } catch (SecurityException e) {
        // Reflection may fail for objects that are in a restricted
        // access package (e.g. sun.*). If we get a security
        // exception, try again with the static type if it is interface.
        // Otherwise, try superclass
        if (staticType != null && staticType.isInterface()) {
          cl = staticType;
          staticType = null; // try staticType only once
        } else {
          Class<?> parent = cl.getSuperclass();
          if (parent == null) {
            if (cl.isInterface()) {
              // last resort after failed staticType interface
              parent = ScriptRuntime.ObjectClass;
            } else {
              throw e;
            }
          }
          cl = parent;
        }
      }
    }

    if (cache.isCachingEnabled()) {
      ct.put(cl, members);
      if (cl != dynamicType) {
        // member lookup for the original class failed because of
        // missing privileges, cache the result so we don't try again
        ct.put(dynamicType, members);
      }
    }
    return members;
  }
 @SuppressWarnings("rawtypes")
 private <O extends Operator> O newInstance(Class<O> c) {
   if (c.isInterface()) {
     return null;
   }
   if (Modifier.isAbstract(c.getModifiers())) {
     return null;
   }
   final Class<?>[] paramTypes;
   final Object[] args;
   if (Modifier.isStatic(c.getModifiers())) {
     paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
     args = ArrayUtils.EMPTY_OBJECT_ARRAY;
   } else {
     paramTypes = new Class[] {getClass()};
     args = new Object[] {this};
   }
   final Constructor<O> cs = ConstructorUtils.getMatchingAccessibleConstructor(c, paramTypes);
   if (cs == null) {
     return null;
   }
   try {
     return cs.newInstance(args);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 @Override
 public <T> void extract(ModelSchemaExtractionContext<T> extractionContext) {
   Type type = extractionContext.getType().getType();
   if (!(type instanceof Class)) {
     return;
   }
   Class<?> contractType = (Class<?>) type;
   if (!contractType.isInterface()) {
     return;
   }
   if (contractType.getGenericInterfaces().length != 1) {
     return;
   }
   Type superType = contractType.getGenericInterfaces()[0];
   if (!(superType instanceof ParameterizedType)) {
     return;
   }
   ParameterizedType parameterizedSuperType = (ParameterizedType) superType;
   if (!parameterizedSuperType.getRawType().equals(ModelMap.class)) {
     return;
   }
   ModelType<?> elementType = ModelType.of(parameterizedSuperType.getActualTypeArguments()[0]);
   Class<?> proxyImpl = generator.generate(ModelMapGroovyDecorator.Managed.class, contractType);
   extractionContext.found(
       new SpecializedMapSchema<T>(extractionContext.getType(), elementType, proxyImpl));
 }
Example #7
1
  protected <T> T getProxy(final Class<T> proxyClass) {
    if (proxyClass == null || Modifier.isFinal(proxyClass.getModifiers())) {
      return null;
    }

    return proxyClass.isInterface() ? proxyForInterface(proxyClass) : proxyForClass(proxyClass);
  }
 private void processImplementation(BeanDefinitionRegistry registry, Class implementation) {
   if (!implementation.isInterface() && !Modifier.isAbstract(implementation.getModifiers())) {
     processRegularClass(registry, implementation);
     addToBeanClassLoader(implementation);
   } else if (implementation.isInterface() && Repository.class.isAssignableFrom(implementation)) {
     processRepositoryInterface(registry, implementation);
     addToBeanClassLoader(implementation);
   } else {
     LOG.warn(
         String.format("Skipping unknown extension point %s", implementation.getCanonicalName()));
   }
 }
Example #9
0
  public static Set<Class<?>> getAllPortableSubtypes(final Class<?> clazz) {
    final Set<Class<?>> portableSubtypes = new HashSet<Class<?>>();
    if (clazz.isInterface() || isPortableType(clazz)) {
      portableSubtypes.add(clazz);
    }

    for (final Class<?> subType : ScannerSingleton.getOrCreateInstance().getSubTypesOf(clazz)) {
      if (clazz.isInterface() || isPortableType(subType)) {
        portableSubtypes.add(subType);
      }
    }

    return portableSubtypes;
  }
Example #10
0
 private static void findCallbacks(Class<?> type, Map<String, Method> result) {
   ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
   if (!type.isInterface()) {
     // No need to search interfaces since interfaces cannot have
     // static methods and callbacks must be static.
     classes.add(type);
   } else {
     Class<?> objCProxy = allObjCProxyClasses.get(type.getName());
     if (objCProxy != null) {
       classes.add(objCProxy);
     }
   }
   try {
     classes.add(Class.forName(type.getName() + "$Callbacks", true, type.getClassLoader()));
   } catch (ClassNotFoundException ignored) {
   }
   for (Class<?> c : classes) {
     for (Method m : c.getDeclaredMethods()) {
       if (m.getAnnotation(Callback.class) != null) {
         BindSelector bindSelector = m.getAnnotation(BindSelector.class);
         if (bindSelector != null) {
           if (!result.containsKey(bindSelector.value())) {
             result.put(bindSelector.value(), m);
           }
         }
       }
     }
   }
 }
Example #11
0
  public static void validatePassivating(Class<?> cl, Bean<?> bean, String typeName) {
    Class<?> beanClass = bean.getBeanClass();

    if (!Serializable.class.isAssignableFrom(beanClass) && false) {
      ConfigException exn =
          new ConfigException(
              L.l(
                  "{0}: {1} is an invalid {2} because it is not serializable.",
                  cl.getName(), bean, typeName));

      throw exn;
      // InjectManager.create().addDefinitionError(exn);
    }

    for (InjectionPoint ip : bean.getInjectionPoints()) {
      if (ip.isTransient() || ip.isDelegate()) continue;

      Class<?> type = getRawClass(ip.getType());

      if (type.isInterface()) continue;

      if (!Serializable.class.isAssignableFrom(type)) {
        ConfigException exn =
            new ConfigException(
                L.l(
                    "{0}: {1} is an invalid {4} because its injection point '{2}' of type {3} is not serializable.",
                    cl.getName(), bean, ip.getMember().getName(), ip.getType(), typeName));

        throw exn;
      }
    }
  }
 /**
  * @param expectedType expected Type
  * @return a {@link EntityFactory} instance for specified type.
  * @throws NullPointerException if expectedType
  * @throws IllegalArgumentException if no factory can be provided
  */
 @SuppressWarnings("unchecked")
 public <T> EntityFactory<T> newInstance(final Class<T> expectedType)
     throws NullPointerException, IllegalArgumentException {
   // in a registered factory ?
   EntityFactories.EntityFactory<?> factory = factories.get(expectedType);
   if (factory == null) {
     // should we use a proxy ?
     if (expectedType.isInterface() || Modifier.isAbstract(expectedType.getModifiers())) {
       final MetaEntityContext metaEntityContext =
           metaEntityContextProvider.find(Reference.newReferenceOnEntityClass(expectedType));
       factory = EntityFactories.newEntityProxyDynamicFactory(expectedType, metaEntityContext);
     } else // EntityDynamic
     if (EntityDynamic.class.getName().equals(expectedType.getName())) {
       // build factory for class
       factory = EntityFactories.newEntityDynamicFactory(MetaModel.getEntityDynamicContext());
     } else // default Factory ?
     {
       if (!enableDefaultFactory) {
         throw new IllegalArgumentException(
             StringUtils.format("No EntityFactory for %s", expectedType));
       }
       if (!Entity.class.isAssignableFrom(expectedType)) {
         throw new IllegalArgumentException(
             StringUtils.format(
                 "No EntityFactory can be created for %s (Not assignable to Entity interface)",
                 expectedType));
       }
       factory = buildDefaultEntityFactory(expectedType);
     }
     // register for later
     factories.put(expectedType, factory);
   }
   return (EntityFactory<T>) factory;
 }
Example #13
0
  @SuppressWarnings("unchecked")
  private Object toValue(Object bean, Field field, XMLNode node) throws Exception {
    Class<?> type = field.getType();

    field.setAccessible(true);
    Object current = field.get(bean);
    if (current != null) type = current.getClass();

    if (Collection.class.isAssignableFrom(type)) {
      Type eleParamType = Object.class;
      ParameterizedType paramType = (ParameterizedType) field.getGenericType();
      if (paramType.getActualTypeArguments().length > 0) {
        eleParamType = paramType.getActualTypeArguments()[0];
      }
      Object[] array = (Object[]) toArrayValues((Class<?>) eleParamType, node);
      Collection collection = null;

      if (current != null && current instanceof Collection) {
        collection = (Collection) current;
      } else if (type.isInterface()) {
        collection = new ArrayList<Object>();
      } else {
        collection = (Collection) type.newInstance();
      }
      Collections.addAll(collection, array);
      return collection;
    }

    if (type.isArray()) return toArrayValues(type, node);

    return toValue(type, node);
  }
Example #14
0
 @Override
 public Object __tojava__(Class<?> c) {
   // Automatically coerce to single method interfaces
   if (c.isInstance(this) && c != InvocationHandler.class) {
     // for base types, conversion is simple - so don't wrap!
     // InvocationHandler is special, since it's a single method interface
     // that we implement, but if we coerce to it we want the arguments
     return c.cast(this);
   } else if (c.isInterface()) {
     if (c.getDeclaredMethods().length == 1 && c.getInterfaces().length == 0) {
       // Proper single method interface
       return proxy(c);
     } else {
       // Try coerce to interface with multiple overloaded versions of
       // the same method (name)
       String name = null;
       for (Method method : c.getMethods()) {
         if (method.getDeclaringClass() != Object.class) {
           if (name == null || name.equals(method.getName())) {
             name = method.getName();
           } else {
             name = null;
             break;
           }
         }
       }
       if (name != null) { // single unique method name
         return proxy(c);
       }
     }
   }
   return super.__tojava__(c);
 }
  private Collection createList() throws IOException {
    Collection list = null;

    if (_type == null) list = new ArrayList();
    else if (!_type.isInterface()) {
      try {
        list = (Collection) _type.newInstance();
      } catch (Exception e) {
      }
    }

    if (list != null) {
    } else if (SortedSet.class.isAssignableFrom(_type)) list = new TreeSet();
    else if (Set.class.isAssignableFrom(_type)) list = new HashSet();
    else if (List.class.isAssignableFrom(_type)) list = new ArrayList();
    else if (Collection.class.isAssignableFrom(_type)) list = new ArrayList();
    else {
      try {
        list = (Collection) _type.newInstance();
      } catch (Exception e) {
        throw new IOExceptionWrapper(e);
      }
    }

    return list;
  }
Example #16
0
  /**
   * Checks if the class under test has compliant modifiers compared to the API.
   *
   * @return true if modifiers are compliant.
   */
  private boolean checkClassModifiersCompliance() {
    int reflectionModifier = mClass.getModifiers();
    int apiModifier = mModifier;

    // If the api class isn't abstract
    if (((apiModifier & Modifier.ABSTRACT) == 0)
        &&
        // but the reflected class is
        ((reflectionModifier & Modifier.ABSTRACT) != 0)
        &&
        // and it isn't an enum
        !isEnumType()) {
      // that is a problem
      return false;
    }
    // ABSTRACT check passed, so mask off ABSTRACT
    reflectionModifier &= ~Modifier.ABSTRACT;
    apiModifier &= ~Modifier.ABSTRACT;

    if (isAnnotation()) {
      reflectionModifier &= ~CLASS_MODIFIER_ANNOTATION;
    }
    if (mClass.isInterface()) {
      reflectionModifier &= ~(Modifier.INTERFACE);
    }
    if (isEnumType() && mClass.isEnum()) {
      reflectionModifier &= ~CLASS_MODIFIER_ENUM;
    }

    return ((reflectionModifier == apiModifier) && (isEnumType() == mClass.isEnum()));
  }
Example #17
0
  @Override
  @SuppressWarnings("unchecked")
  public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
    Class<T> typeToMock = settings.getTypeToMock();
    @SuppressWarnings("rawtypes")
    Set<Class> interfacesSet = settings.getExtraInterfaces();
    Class<?>[] extraInterfaces = interfacesSet.toArray(new Class[interfacesSet.size()]);
    InvocationHandler invocationHandler = new InvocationHandlerAdapter(handler);

    if (typeToMock.isInterface()) {
      // support interfaces via java.lang.reflect.Proxy
      @SuppressWarnings("rawtypes")
      Class[] classesToMock = new Class[extraInterfaces.length + 1];
      classesToMock[0] = typeToMock;
      System.arraycopy(extraInterfaces, 0, classesToMock, 1, extraInterfaces.length);
      ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
      // newProxyInstance returns the type of typeToMock
      T mock = (T) Proxy.newProxyInstance(contextClassLoader, classesToMock, invocationHandler);
      return mock;

    } else {
      try {
        Class<? extends T> proxyClass = getProxyClass(typeToMock, extraInterfaces);
        T mock = proxyClass.newInstance();
        ((ClassProxy) mock).setHandler(invocationHandler);
        return mock;
      } catch (RuntimeException e) {
        throw e;
      } catch (Exception e) {
        throw new MockitoException("Failed to mock " + typeToMock, e);
      }
    }
  }
Example #18
0
 /**
  * Algorithm that judges the match between the declared parameter types of a candidate method and
  * a specific list of arguments that this method is supposed to be invoked with.
  *
  * <p>Determines a weight that represents the class hierarchy difference between types and
  * arguments. A direct match, i.e. type Integer - arg of class Integer, does not increase the
  * result - all direct matches means weight 0. A match between type Object and arg of class
  * Integer would increase the weight by 2, due to the superclass 2 steps up in the hierarchy (i.e.
  * Object) being the last one that still matches the required type Object. Type Number and class
  * Integer would increase the weight by 1 accordingly, due to the superclass 1 step up the
  * hierarchy (i.e. Number) still matching the required type Number. Therefore, with an arg of type
  * Integer, a constructor (Integer) would be preferred to a constructor (Number) which would in
  * turn be preferred to a constructor (Object). All argument weights get accumulated.
  *
  * <p>Note: This is the algorithm used by MethodInvoker itself and also the algorithm used for
  * constructor and factory method selection in Spring's bean container (in case of lenient
  * constructor resolution which is the default for regular bean definitions).
  *
  * @param paramTypes the parameter types to match
  * @param args the arguments to match
  * @return the accumulated weight for all arguments
  */
 public static int getTypeDifferenceWeight(Class<?>[] paramTypes, Object[] args) {
   int result = 0;
   for (int i = 0; i < paramTypes.length; i++) {
     if (!ClassUtils.isAssignableValue(paramTypes[i], args[i])) {
       return Integer.MAX_VALUE;
     }
     if (args[i] != null) {
       Class<?> paramType = paramTypes[i];
       Class<?> superClass = args[i].getClass().getSuperclass();
       while (superClass != null) {
         if (paramType.equals(superClass)) {
           result = result + 2;
           superClass = null;
         } else if (ClassUtils.isAssignable(paramType, superClass)) {
           result = result + 2;
           superClass = superClass.getSuperclass();
         } else {
           superClass = null;
         }
       }
       if (paramType.isInterface()) {
         result = result + 1;
       }
     }
   }
   return result;
 }
Example #19
0
 private void checkContextMethod(Method m, Object provider) {
   Class<?> type = m.getParameterTypes()[0];
   if (type.isInterface() || type == Application.class) {
     checkContextClass(type);
     addContextMethod(type, m, provider);
   }
 }
Example #20
0
 /**
  * Gets the number of steps required needed to turn the source class into the destination class.
  * This represents the number of steps in the object hierarchy graph.
  *
  * @param srcClass The source class
  * @param destClass The destination class
  * @return The cost of transforming an object
  */
 private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
   if (destClass.isPrimitive()) {
     return getPrimitivePromotionCost(srcClass, destClass);
   }
   float cost = 0.0f;
   while (srcClass != null && !destClass.equals(srcClass)) {
     if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
       // slight penalty for interface match.
       // we still want an exact match to override an interface match,
       // but
       // an interface match should override anything where we have to
       // get a superclass.
       cost += 0.25f;
       break;
     }
     cost++;
     srcClass = srcClass.getSuperclass();
   }
   /*
    * If the destination class is null, we've travelled all the way up to
    * an Object match. We'll penalize this by adding 1.5 to the cost.
    */
   if (srcClass == null) {
     cost += 1.5f;
   }
   return cost;
 }
Example #21
0
  private static void generateGetValue(
      Class owner,
      Type ownerType,
      Method method,
      boolean isStatic,
      Type resolvableType,
      Type[] arguments,
      MxGeneratorAdapter getValue,
      TransformGenerator[] tg,
      Type[] stored) {
    getValue.visitCode();

    if (!isStatic) {
      getValue.loadThis();
      getValue.getField(resolvableType, OWNER_FIELD_NAME, ownerType);
    }
    int index = 0;
    for (int i = 0; i < arguments.length; i++) {
      getValue.loadThis();
      getValue.getField(resolvableType, "arg" + i, stored[i]);
      if (tg != null) {
        tg[i].generateBackward(resolvableType, index, getValue);
        index += tg[i].getFieldCount();
      }
    }

    getValue.visitMethodInsn(
        isStatic ? INVOKESTATIC : owner.isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL,
        ownerType.getInternalName(),
        method.getName(),
        method.getDescriptor());
    getValue.returnValue();
    getValue.endMethod();
  }
  public static List<String> validateClass(Class<? extends Messages> classUnderTest)
      throws URISyntaxException, IOException {
    List<String> errors = new ArrayList<String>();

    if (classUnderTest.isInterface()) {
      File messagesDir =
          new File(classUnderTest.getResource(".").toURI().toASCIIString().replaceAll("file:", ""));
      List<Method> messagesMethods = Arrays.asList(classUnderTest.getMethods());

      File[] propertiesFiles =
          getMessagesPropertiesFiles(messagesDir, classUnderTest.getSimpleName());
      if (propertiesFiles != null) {
        for (File localeFile : propertiesFiles) {
          PropertiesFileInfo.properties = loadProperties(localeFile);
          PropertiesFileInfo.fileName = localeFile.getName();

          for (Method method : messagesMethods) {
            checkForMissingDefault(method, errors);
            checkPlaceHolders(method, errors);
          }
        }
      }
    } else {
      errors.add("Class under test is not an interface: " + classUnderTest.getName());
    }

    return errors;
  }
 @Override
 public DatastoreTable getDatastoreClass(String className, ClassLoaderResolver clr) {
   try {
     // We see the occasional race condition when multiple threads concurrently
     // perform an operation using a persistence-capable class for which DataNucleus
     // has not yet generated the meta-data.  The result is usually
     // AbstractMemberMetaData objects with the same column listed twice in the meta-data.
     // Locking at this level is a bit more coarse-grained than I'd like but once the
     // meta-data has been built this will return super fast so it shouldn't be an issue.
     synchronized (this) {
       return (DatastoreTable) super.getDatastoreClass(className, clr);
     }
   } catch (NoTableManagedException e) {
     // Our parent class throws this when the class isn't PersistenceCapable also.
     Class cls = clr.classForName(className);
     ApiAdapter api = getApiAdapter();
     if (cls != null && !cls.isInterface() && !api.isPersistable(cls)) {
       throw new NoTableManagedException(
           "Class "
               + className
               + " does not seem to have been enhanced. You may want to rerun "
               + "the enhancer and check for errors in the output.");
       // Suggest you address why this method is being called before any check on whether it is
       // persistable
       // then you can remove this error message
     }
     throw e;
   }
 }
Example #24
0
  /**
   * check whether a class should not be considered for transformation
   *
   * @param clazz the class to check
   * @return true if clazz should not be considered for transformation otherwise false
   */
  protected boolean isSkipClass(Class<?> clazz) {
    if (!inst.isModifiableClass(clazz)) {
      return true;
    }

    // we can safely skip array classes, interfaces and primitive classes

    if (clazz.isArray()) {
      return true;
    }

    if (clazz.isInterface()) {
      return true;
    }

    if (clazz.isPrimitive()) {
      return true;
    }

    String name = clazz.getName();

    if (isBytemanClass(name) || !isTransformable(name)) {
      return true;
    }

    return false;
  }
Example #25
0
  /**
   * Construct a new class URI for the given class.
   *
   * @param clazz The class to wrap.
   */
  public ClassURI(Class<? extends Plugin> clazz) {
    if (clazz.isInterface())
      throw new IllegalArgumentException(
          "The paramter must be a concrete plugin class, not a plugin interface.");

    this.clazz = clazz;
  }
Example #26
0
  public T build() {
    Preconditions.checkArgument(null != serviceType, "ServiceType cannot be null.");
    Preconditions.checkArgument(null != clazz, "Service interface cannot be null.");
    Preconditions.checkArgument(clazz.isInterface(), "Service interface must be an interface.");
    if (null == factory) {
      if (null == strategy) {
        strategy = Strategy.RANDOM;
      }
      factory = LoadBalancerSupport.newFactory(strategy);
    }
    ServiceProxyFactory proxyFactory;
    switch (serviceType) {
      case THRIFT:
        proxyFactory = ThriftServiceProxyFactory.getInstance();
        break;
      default:
        throw new IllegalArgumentException("Not supported ServiceType: " + serviceType);
    }
    if (StringUtils.isEmpty(serviceName)) {
      serviceName = ServiceConfigHelper.buildDefaultServiceName(serviceType, clazz);
    }
    if (Strings.isNullOrEmpty(serviceGroup)) {
      serviceGroup = ZookeeperConfig.getServiceGroup(serviceName);
    }
    if (!Strings.isNullOrEmpty(user)) {}

    return proxyFactory.getService(serviceGroup, serviceName, factory, clazz);
  }
 /**
  * Helper method used to find inheritance (implements, extends) path between given types, if one
  * exists (caller generally checks before calling this method). Returned type represents given
  * <b>subtype</b>, with supertype linkage extending to <b>supertype</b>.
  */
 protected static HierarchicType _findSuperTypeChain(Class<?> subtype, Class<?> supertype) {
   // If super-type is a class (not interface), bit simpler
   if (supertype.isInterface()) {
     return _findSuperInterfaceChain(subtype, supertype);
   }
   return _findSuperClassChain(subtype, supertype);
 }
Example #28
0
 protected boolean isAssignableFrom(final Type t, final Type u) {
   if (t.equals(u)) {
     return true;
   }
   if (currentClass != null && t.equals(currentClass)) {
     if (getSuperClass(u) == null) {
       return false;
     } else {
       if (isInterface) {
         return u.getSort() == Type.OBJECT || u.getSort() == Type.ARRAY;
       }
       return isAssignableFrom(t, getSuperClass(u));
     }
   }
   if (currentClass != null && u.equals(currentClass)) {
     if (isAssignableFrom(t, currentSuperClass)) {
       return true;
     }
     if (currentClassInterfaces != null) {
       for (int i = 0; i < currentClassInterfaces.size(); ++i) {
         Type v = currentClassInterfaces.get(i);
         if (isAssignableFrom(t, v)) {
           return true;
         }
       }
     }
     return false;
   }
   Class<?> tc = getClass(t);
   if (tc.isInterface()) {
     tc = Object.class;
   }
   return tc.isAssignableFrom(getClass(u));
 }
Example #29
0
 public static boolean isValidResourceClass(Class<?> c) {
   if (c.isInterface() || Modifier.isAbstract(c.getModifiers())) {
     LOG.info("Ignoring invalid resource class " + c.getName());
     return false;
   }
   return true;
 }
 @Override
 public void visit(
     final int version,
     final int access,
     final String name,
     final String signature,
     final String superName,
     final String[] interfaces) {
   Set<String> interfacesSet = new LinkedHashSet<String>();
   if (interfaces != null) Collections.addAll(interfacesSet, interfaces);
   for (Class extraInterface : classList) {
     if (extraInterface.isInterface())
       interfacesSet.add(BytecodeHelper.getClassInternalName(extraInterface));
   }
   final boolean addGroovyObjectSupport = !GroovyObject.class.isAssignableFrom(superClass);
   if (addGroovyObjectSupport) interfacesSet.add("groovy/lang/GroovyObject");
   super.visit(
       V1_5,
       ACC_PUBLIC,
       proxyName,
       signature,
       BytecodeHelper.getClassInternalName(superClass),
       interfacesSet.toArray(new String[interfacesSet.size()]));
   addDelegateFields();
   if (addGroovyObjectSupport) {
     createGroovyObjectSupport();
   }
   for (Class clazz : classList) {
     visitClass(clazz);
   }
 }