protected <T> T executeCommand(Command cmd) {
    if (AcceptedClientCommands.isSendObjectParameterCommandClass(cmd.getClass())) {
      List<Object> extraClassInstanceList = new ArrayList<Object>();
      preprocessParameterCommand(cmd, extraClassInstanceList);

      if (!extraClassInstanceList.isEmpty()) {
        Set<Class<?>> extraJaxbClasses = new HashSet<Class<?>>();
        for (Object jaxbObject : extraClassInstanceList) {
          Class<?> jaxbClass = jaxbObject.getClass();
          if (jaxbClass.isLocalClass() || jaxbClass.isAnonymousClass()) {
            throw new SerializationException(
                "Only proper classes are allowed as parameters for the remote API: neither local nor anonymous classes are accepted: "
                    + jaxbClass.getName());
          }
          extraJaxbClasses.add(jaxbClass);
        }
        if (config.addJaxbClasses(extraJaxbClasses)) {
          for (Class<?> extraClass : extraJaxbClasses) {
            logger.debug(
                "Adding {} to the JAXBContext instance in this client instance.",
                extraClass.getName());
          }
          config.initializeJaxbSerializationProvider();
        }
      }
    }

    preprocessCommand(cmd);

    if (config.isRest()) {
      return executeRestCommand(cmd);
    } else {
      return executeJmsCommand(cmd);
    }
  }
 @Test
 public void should_generate_assertion_for_classes_in_package_using_provided_class_loader()
     throws Exception {
   ClassLoader customClassLoader =
       new MyClassLoader(Thread.currentThread().getContextClassLoader());
   Set<Class<?>> classes =
       collectClasses(customClassLoader, "org.assertj.assertions.generator.data");
   for (Class<?> clazz : classes) {
     assertThat(clazz.isAnonymousClass())
         .as("check that " + clazz.getSimpleName() + " is not anonymous")
         .isFalse();
     assertThat(clazz.isLocalClass())
         .as("check that " + clazz.getSimpleName() + " is not local")
         .isFalse();
     assertThat(isPublic(clazz.getModifiers()))
         .as("check that " + clazz.getSimpleName() + " is public")
         .isTrue();
     logger.info("Generating assertions for {}", clazz.getName());
     final ClassDescription classDescription = converter.convertToClassDescription(clazz);
     File customAssertionFile = assertionGenerator.generateCustomAssertionFor(classDescription);
     logger.info(
         "Generated {} assertions file -> {}",
         clazz.getSimpleName(),
         customAssertionFile.getAbsolutePath());
   }
 }
Example #3
1
  @SuppressWarnings("unchecked")
  static void annotatedWith(Set<Class<?>> contracts, Object obj, Class annotation) {
    if (null != obj) {
      Class<?> clazz = obj.getClass();

      while (Object.class != clazz) {
        if (!clazz.isAnonymousClass()) {
          Object t = clazz.getAnnotation(annotation);
          if (null != t) {
            contracts.add(clazz);
          } else {
            annotatedWith(contracts, annotation, clazz);
          }

          for (Class<?> iface : clazz.getInterfaces()) {
            t = iface.getAnnotation(annotation);
            if (null != t) {
              contracts.add(iface);
            } else {
              annotatedWith(contracts, annotation, iface);
            }
          }
        }

        clazz = clazz.getSuperclass();
      }
    }
  }
Example #4
1
  private static String approximateSimpleName(Class<?> clazz, boolean dropOuterClassNames) {
    checkArgument(!clazz.isAnonymousClass(), "Attempted to get simple name of anonymous class");

    String fullName = clazz.getName();
    String shortName = fullName.substring(fullName.lastIndexOf('.') + 1);

    // Drop common suffixes for each named component.
    String[] names = shortName.split("\\$");
    for (int i = 0; i < names.length; i++) {
      names[i] = simplifyNameComponent(names[i]);
    }
    shortName = Joiner.on('$').join(names);

    if (dropOuterClassNames) {
      // Simplify inner class name by dropping outer class prefixes.
      Matcher m = NAMED_INNER_CLASS.matcher(shortName);
      if (m.matches()) {
        shortName = m.group("INNER");
      }
    } else {
      // Dropping anonymous outer classes
      shortName = shortName.replaceAll(ANONYMOUS_CLASS_REGEX, ".");
      shortName = shortName.replaceAll("\\$", ".");
    }
    return shortName;
  }
Example #5
1
  /**
   * Replaces an anonymous inner class with a serializable substitution based on its {@code
   * writeReplace} method.
   *
   * @param object the object to substitute, not null
   * @return the substitution object as returned by its {@code writeReplace} method
   * @throws OpenGammaRuntimeException if no suitable method is defined or an error occurs in its
   *     execution
   */
  protected static Object substituteObject(final Object object) {
    final Class<?> clazz = object.getClass();
    if (clazz.isAnonymousClass()) {
      Method method = s_writeReplace.get(clazz);
      if (method == null) {
        method =
            AccessController.doPrivileged(
                new PrivilegedAction<Method>() {

                  @Override
                  public Method run() {
                    try {
                      final Method mtd = clazz.getMethod("writeReplace");
                      mtd.setAccessible(true);
                      return mtd;
                    } catch (NoSuchMethodException e) {
                      // Ignore
                    }
                    return null;
                  }
                });
        if (method == null) {
          throw new OpenGammaRuntimeException(
              "No serialization substitution available for anonymous inner class object " + object);
        }
        s_writeReplace.putIfAbsent(clazz, method);
      }
      try {
        return method.invoke(object);
      } catch (Exception e) {
        throw new OpenGammaRuntimeException("Couldn't call writeReplace on inner class", e);
      }
    }
    return object;
  }
  /**
   * Default constructor associates this handler with the queue for the current thread.
   *
   * <p>If there isn't one, this handler won't be able to receive messages.
   */
  public Handler() {
    if (FIND_POTENTIAL_LEAKS) {
      final Class<? extends Handler> klass = getClass();
      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass())
          && (klass.getModifiers() & Modifier.STATIC) == 0) {
        Log.w(
            TAG,
            "The following Handler class should be static or leaks might occur: "
                + klass.getCanonicalName());
      }
    }
    // @wujl commented

    mLooper = Looper.myLooper();
    if (mLooper == null) {
      throw new RuntimeException(
          "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;

    // #wujl
    // @wujl added
    // mLooper = null;
    // mQueue = null;
    // #wujl
    mCallback = null;
  }
Example #7
1
 private boolean checkAnonymous(Class<?> target) {
   if (!target.isAnonymousClass()) {
     return false;
   }
   if (target.getSuperclass() != Object.class && target.getSuperclass() == javaClass) {
     return true;
   }
   if (target.getInterfaces().length == 1 && target.getInterfaces()[0] == javaClass) {
     return true;
   }
   return false;
 }
Example #8
0
  public static String stringify(Object obj) {
    if (obj instanceof Object[])
      if (obj instanceof Iterable) {
        return stringify((Iterable) obj);
      }

    if (obj instanceof IStringSerializable) {
      return ((IStringSerializable) obj).getName();
    }

    String data = "";

    if (obj instanceof Item) {
      data += "name = " + ((Item) obj).getUnlocalizedName();
    } else if (obj instanceof Block) {
      data += "name = " + ((Block) obj).getUnlocalizedName();
    } else if (obj instanceof Class) {
      Class clazz = (Class) obj;
      String name = clazz.getSimpleName();

      if (clazz.isAnonymousClass()) {
        name = clazz.getSuperclass().getSimpleName();
      }

      data += "name = " + name;
    }

    return obj.getClass().getSimpleName() + (data.length() > 0 ? "(" + data + ")" : "");
  }
  /*
   * TODO: Profiling shows that the reflection and conditional logic in this
   * method is a hotspot. This could be remedied by generating synthetic
   * InstantiateCommand types that initialize themselves.
   */
  private IdentityValueCommand makeObject(Class<?> type, Object value)
      throws SerializationException {

    if (type.isAnonymousClass() || type.isLocalClass()) {
      throw new SerializationException("Cannot serialize anonymous or local classes");
    }

    Class<?> manualType = type;
    Class<?> customSerializer;
    do {
      customSerializer = SerializabilityUtil.hasCustomFieldSerializer(manualType);
      if (customSerializer != null) {
        break;
      }
      manualType = manualType.getSuperclass();
    } while (manualType != null);

    IdentityValueCommand ins;
    if (customSerializer != null) {
      ins = serializeWithCustomSerializer(customSerializer, value, type, manualType);
    } else {
      ins = new InstantiateCommand(type);
      identityMap.put(value, ins);
    }

    /*
     * If we're looking at a subclass of a manually-serialized type, the
     * subclass must be tagged as serializable in order to qualify for
     * serialization.
     */
    if (type != manualType) {
      if (!Serializable.class.isAssignableFrom(type)
          && !IsSerializable.class.isAssignableFrom(type)) {
        throw new SerializationException(type.getName() + " is not a serializable type");
      }
    }

    while (type != manualType) {
      Field[] serializableFields = clientOracle.getOperableFields(type);
      for (Field declField : serializableFields) {
        assert (declField != null);

        Accessor accessor = CommandSerializationUtil.getAccessor(declField.getType());
        ValueCommand valueCommand;
        Object fieldValue = accessor.get(value, declField);
        if (fieldValue == null) {
          valueCommand = NullValueCommand.INSTANCE;
        } else {
          Class<? extends Object> fieldType =
              declField.getType().isPrimitive() ? declField.getType() : fieldValue.getClass();
          valueCommand = makeValue(fieldType, fieldValue);
        }

        ((HasSetters) ins).set(declField.getDeclaringClass(), declField.getName(), valueCommand);
      }
      type = type.getSuperclass();
    }
    return ins;
  }
Example #10
0
  private static void classToXML(
      Document xmldoc, Element parent, Class<?> clazz, String preAppendToSimpleClassName)
      throws Exception {

    boolean isConcreteClass = (clazz.getModifiers() & Modifier.ABSTRACT) == 0;
    if (isConcreteClass && !clazz.isAnonymousClass()) {
      parent.appendChild(createXMLTree(xmldoc, clazz, preAppendToSimpleClassName));
    }
  }
Example #11
0
 public void registerAliases(String packageName, Class superType) {
   ResolverUtil<Class> resolverUtil = new ResolverUtil<Class>();
   resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
   Set<Class<? extends Class>> typeSet = resolverUtil.getClasses();
   for (Class type : typeSet) {
     // Ignore inner classes
     if (!type.isAnonymousClass()) registerAlias(type.getSimpleName(), type);
   }
 }
Example #12
0
 public static boolean isCacheable(Annotation[] annotations) {
   for (Annotation qualifier : annotations) {
     Class<?> clazz = qualifier.getClass();
     if (clazz.isAnonymousClass() || (clazz.isMemberClass() && isStatic(clazz))) {
       return false;
     }
   }
   return true;
 }
  /**
   * 注册类到Guice
   *
   * @param binder
   * @param classToBind
   */
  private void bindClass(final Binder binder, final Class classToBind) {

    // don't bind anonymous classes  匿名内部类
    if (classToBind.isAnonymousClass()) return;

    // don't bind annotations 注解定义类
    if (classToBind.isAnnotation()) return;

    binder.bind(classToBind);
  }
Example #14
0
  public static boolean isAnnotationReturnType(Class cls) {
    // TODO review this calculation
    Class targetType = cls;
    if (cls.isArray() && (targetType = cls.getComponentType()).isArray()) {
      return false;
    }

    return (targetType.isAnnotation() || targetType.isEnum() || targetType.isPrimitive())
        || (!targetType.isAnonymousClass() && !targetType.isLocalClass());
  }
Example #15
0
  @Override
  public String getIdPrefix() {
    Class<?> clazz = getClass();

    if (clazz.isAnonymousClass()) {
      return "a";
    } else {
      return clazz.getSimpleName().substring(0, 1);
    }
  }
Example #16
0
  static <T extends Annotation> T annotation(Object obj, Class<T> annotation) {
    if (null == obj) {
      return null;
    }

    Class<?> clazz = obj.getClass();
    if (Proxy.isProxyClass(clazz) || clazz.isAnonymousClass()) {
      for (Class<?> iface : clazz.getInterfaces()) {
        T t = iface.getAnnotation(annotation);
        if (null != t) {
          return t;
        }
      }

      if (clazz.isAnonymousClass()) {
        clazz = clazz.getSuperclass();
      }
    }

    return clazz.getAnnotation(annotation);
  }
 public void register(String packageName) {
   ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
   resolverUtil.find(new ResolverUtil.IsA(TypeHandler.class), packageName);
   Set<Class<? extends Class<?>>> handlerSet = resolverUtil.getClasses();
   for (Class<?> type : handlerSet) {
     // Ignore inner classes and interfaces (including package-info.java) and abstract classes
     if (!type.isAnonymousClass()
         && !type.isInterface()
         && !Modifier.isAbstract(type.getModifiers())) {
       register(type);
     }
   }
 }
 private boolean assertFinal() {
   try {
     final Class<?> clazz = getClass();
     if (!clazz.desiredAssertionStatus()) return true;
     assert clazz.isAnonymousClass()
             || (clazz.getModifiers() & (Modifier.FINAL | Modifier.PRIVATE)) != 0
             || Modifier.isFinal(clazz.getMethod("incrementToken").getModifiers())
         : "TokenStream implementation classes or at least their incrementToken() implementation must be final";
     return true;
   } catch (NoSuchMethodException nsme) {
     return false;
   }
 }
Example #19
0
 public TypeReference(final Class<?> clazz, final List<TypeReference> arguments) {
   boolean _isPrimitive = clazz.isPrimitive();
   if (_isPrimitive) {
     String _name = clazz.getName();
     String _plus = ("Type is primitive: " + _name);
     throw new IllegalArgumentException(_plus);
   }
   boolean _isAnonymousClass = clazz.isAnonymousClass();
   if (_isAnonymousClass) {
     String _name_1 = clazz.getName();
     String _plus_1 = ("Class is anonymous: " + _name_1);
     throw new IllegalArgumentException(_plus_1);
   }
   boolean _isLocalClass = clazz.isLocalClass();
   if (_isLocalClass) {
     String _name_2 = clazz.getName();
     String _plus_2 = ("Class is local: " + _name_2);
     throw new IllegalArgumentException(_plus_2);
   }
   Package _package = clazz.getPackage();
   String _name_3 = _package.getName();
   this.packageName = _name_3;
   ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList();
   this.simpleNames = _newArrayList;
   List<TypeReference> _elvis = null;
   if (arguments != null) {
     _elvis = arguments;
   } else {
     List<TypeReference> _emptyList = Collections.<TypeReference>emptyList();
     _elvis = _emptyList;
   }
   this.typeArguments = _elvis;
   Class<?> c = clazz;
   do {
     {
       String _simpleName = c.getSimpleName();
       this.simpleNames.add(0, _simpleName);
       Class<?> _declaringClass = c.getDeclaringClass();
       c = _declaringClass;
     }
   } while ((c != null));
 }
Example #20
0
  /**
   * @return Return true if the given type can be managed by the driver, and subsequently by the UI.
   *     <p>E.g. of managed types are: int, Integer, java.lang.Integer, org.kie.SomeClass,
   *     List<Integer>, java.util.List<org.kie.SomeClass>
   *     <p>e.g. of not manged types are: int[], java.util.List<List<String>>, List<Map<String,
   *     org.kie.SomeClass>>
   */
  public static boolean isManagedType(Type type, ClassTypeResolver classTypeResolver)
      throws ModelDriverException {

    // quickest checks first.
    if (type.isPrimitive()) {
      return true;
    }

    if (type.isArray()) {
      return false;
    }

    if (type.isParameterized() && type.getTypeArguments().size() > 1) {
      return false;
    }

    try {

      Class<?> clazz = classTypeResolver.resolveType(type.getName());

      if (clazz.isAnonymousClass() || clazz.isLocalClass() || clazz.isMemberClass()) {
        return false;
      }

      if (type.isParameterized()) {
        Class<?> bag = classTypeResolver.resolveType(type.getName());
        if (!Collection.class.isAssignableFrom(bag)) {
          return false;
        }

        return isSimpleClass(((List<Type>) type.getTypeArguments()).get(0));
      }

      return true;

    } catch (ClassNotFoundException e) {
      throw new ModelDriverException(
          "Class could not be resolved for name: " + type.getName() + ". " + e.getMessage(), e);
    }
  }
  private static void addFromClasspath(Set<Class<? extends Module>> modules) {
    ClassClassLoaderResolver<Module> resolver = new ClassClassLoaderResolver<Module>();
    Set<Class<Module>> moduleClasses;
    try {
      moduleClasses =
          resolver.findByLocators(
              new ClassClassLoaderResolver.IsA(Module.class),
              false,
              GuiceContainer.guiceExcludeModules,
              "guice");
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    Set<Class<Module>> matches = new HashSet<Class<Module>>(moduleClasses);

    for (Class<Module> moduleClass : moduleClasses) {
      // Ensure the class is not abstract
      if ((moduleClass.getModifiers() & Modifier.ABSTRACT) != 0
          || moduleClass.isAnonymousClass()
          || moduleClass.isLocalClass()) {
        matches.remove(moduleClass);
        continue;
      }

      // Remove any instances of this classes parents from the matches
      Class<?> parent = moduleClass.getSuperclass();
      while (Module.class.isAssignableFrom(parent)) {
        matches.remove(parent);
        parent = parent.getSuperclass();
      }
    }

    for (Class<Module> match : matches) {
      logger.info("Adding module [" + match + "] from classpath to Guice injector.");
    }

    modules.addAll(matches);
  }
  /**
   * Creates {@link gobblin.metrics.MetricContext}. Tries to read the name of the parent context
   * from key "metrics.context.name" at state, and tries to get the parent context by name from the
   * {@link gobblin.metrics.MetricContext} registry (the parent context must be registered).
   *
   * <p>Automatically adds two tags to the inner context:
   *
   * <ul>
   *   <li>component: attempts to determine which component type within gobblin-api generated this
   *       instance.
   *   <li>class: the specific class of the object that generated this instance of Instrumented
   * </ul>
   */
  public MetricContext getMetricContext(State state, Class<?> klazz, List<Tag<?>> tags) {
    int randomId = new Random().nextInt(Integer.MAX_VALUE);

    List<Tag<?>> generatedTags = Lists.newArrayList();

    if (!klazz.isAnonymousClass()) {
      generatedTags.add(new Tag<>("class", klazz.getCanonicalName()));
    }

    Optional<GobblinMetrics> gobblinMetrics =
        state.contains(ConfigurationKeys.METRIC_CONTEXT_NAME_KEY)
            ? GobblinMetricsRegistry.getInstance()
                .get(state.getProp(ConfigurationKeys.METRIC_CONTEXT_NAME_KEY))
            : Optional.<GobblinMetrics>absent();

    MetricContext.Builder builder =
        gobblinMetrics.isPresent()
            ? gobblinMetrics
                .get()
                .getMetricContext()
                .childBuilder(klazz.getCanonicalName() + "." + randomId)
            : MetricContext.builder(klazz.getCanonicalName() + "." + randomId);
    return builder.addTags(generatedTags).addTags(tags).build();
  }
  @SuppressWarnings("rawtypes")
  @Test
  public void searchAndTest() {
    Reflections reflections = new Reflections("org.estatio.dom");

    System.out.println("EstatioDomainObjectContractTestAll_jdoAnnotations");

    Set<Class<? extends UdoDomainObject>> subtypes =
        reflections.getSubTypesOf(UdoDomainObject.class);
    for (Class<? extends UdoDomainObject> subtype : subtypes) {
      if (subtype.isAnonymousClass()
          || subtype.isLocalClass()
          || subtype.isMemberClass()
          || subtype.getName().endsWith("ForTesting")) {
        // skip (probably a testing class)
        continue;
      }
      if (UdoDomainObject.class == subtype || EstatioDomainObject.class == subtype) {
        // skip
        continue;
      }

      System.out.println(">>> " + subtype.getName());

      // must have a @PersistenceCapable(identityType=...) annotation
      final PersistenceCapable persistenceCapable = subtype.getAnnotation(PersistenceCapable.class);
      assertThat(
          "Class "
              + subtype.getName()
              + " inherits from EstatioDomainObject "
              + "but is not annotated with @PersistenceCapable",
          persistenceCapable,
          is(not(nullValue())));
      IdentityType identityType = persistenceCapable.identityType();
      assertThat(
          "Class "
              + subtype.getName()
              + " @PersistenceCapable annotation "
              + "does not specify the identityType",
          identityType,
          is(not(nullValue())));

      if (identityType == IdentityType.DATASTORE) {
        // NOT mandatory to have a @DatastoreIdentity, but if does, then @DatastoreIdentity(...,
        // column="id")
        final DatastoreIdentity datastoreIdentity = subtype.getAnnotation(DatastoreIdentity.class);
        if (datastoreIdentity != null) {
          assertThat(
              "Class "
                  + subtype.getName()
                  + " @DataStoreIdentity annotation does not specify column=\"id\"",
              datastoreIdentity.column(),
              is("id"));
        }
      }

      Inheritance inheritance = subtype.getAnnotation(Inheritance.class);

      if (inheritance != null && inheritance.strategy() == InheritanceStrategy.SUPERCLASS_TABLE) {
        // must NOT have a @Discriminator(..., column="discriminator")
        final Annotation[] declaredAnnotations = subtype.getDeclaredAnnotations();
        for (Annotation declaredAnnotation : declaredAnnotations) {
          if (declaredAnnotation.annotationType() == Discriminator.class) {
            Assert.fail(
                "Class "
                    + subtype.getName()
                    + " inherits from "
                    + subtype.getSuperclass().getName()
                    + "and has (incorrectly) been annotated with @Discriminator");
          }
        }

        // check if supertype has discriminator

        // must have a @Discriminator(..., column="discriminator") on one of its supertypes
        final Discriminator superDiscriminator =
            subtype.getSuperclass().getAnnotation(Discriminator.class);
        assertThat(
            "Class "
                + subtype.getSuperclass().getName()
                + " is inherited by "
                + subtype.getName()
                + "but is not annotated with @Discriminator",
            superDiscriminator,
            is(not(nullValue())));

        assertThat(
            "Class "
                + subtype.getName()
                + " @Discriminator annotation does not specify column=\"discriminator\"",
            superDiscriminator.column(),
            is("discriminator"));
      }

      if (subtype.getSuperclass().equals(UdoDomainObject.class)) {
        // must have a @Version(..., column="version")
        final Version version = getAnnotationOfTypeOfItsSupertypes(subtype, Version.class);

        assertThat(
            "Class "
                + subtype.getName()
                + " inherits from EstatioMutableObject "
                + "but is not annotated with @Version",
            version,
            is(not(nullValue())));

        assertThat(
            "Class "
                + subtype.getName()
                + " @Version annotation does not specify have column=\"version\"",
            version.column(),
            is("version"));
      }
    }
  }
Example #24
0
  @BeforeClass
  public static void beforeClass() throws Exception {
    List<Class<?>> analysisClasses = getClassesForPackage("org.apache.lucene.analysis");
    tokenizers = new ArrayList<Constructor<? extends Tokenizer>>();
    tokenfilters = new ArrayList<Constructor<? extends TokenFilter>>();
    charfilters = new ArrayList<Constructor<? extends CharFilter>>();
    for (final Class<?> c : analysisClasses) {
      final int modifiers = c.getModifiers();
      if (
      // don't waste time with abstract classes or deprecated known-buggy ones
      Modifier.isAbstract(modifiers)
          || !Modifier.isPublic(modifiers)
          || c.isSynthetic()
          || c.isAnonymousClass()
          || c.isMemberClass()
          || c.isInterface()
          || c.isAnnotationPresent(Deprecated.class)
          || !(Tokenizer.class.isAssignableFrom(c)
              || TokenFilter.class.isAssignableFrom(c)
              || CharFilter.class.isAssignableFrom(c))) {
        continue;
      }

      for (final Constructor<?> ctor : c.getConstructors()) {
        // don't test synthetic or deprecated ctors, they likely have known bugs:
        if (ctor.isSynthetic()
            || ctor.isAnnotationPresent(Deprecated.class)
            || brokenConstructors.get(ctor) == ALWAYS) {
          continue;
        }
        if (Tokenizer.class.isAssignableFrom(c)) {
          assertTrue(
              ctor.toGenericString() + " has unsupported parameter types",
              allowedTokenizerArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
          tokenizers.add(castConstructor(Tokenizer.class, ctor));
        } else if (TokenFilter.class.isAssignableFrom(c)) {
          assertTrue(
              ctor.toGenericString() + " has unsupported parameter types",
              allowedTokenFilterArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
          tokenfilters.add(castConstructor(TokenFilter.class, ctor));
        } else if (CharFilter.class.isAssignableFrom(c)) {
          assertTrue(
              ctor.toGenericString() + " has unsupported parameter types",
              allowedCharFilterArgs.containsAll(Arrays.asList(ctor.getParameterTypes())));
          charfilters.add(castConstructor(CharFilter.class, ctor));
        } else {
          fail("Cannot get here");
        }
      }
    }

    final Comparator<Constructor<?>> ctorComp =
        new Comparator<Constructor<?>>() {
          @Override
          public int compare(Constructor<?> arg0, Constructor<?> arg1) {
            return arg0.toGenericString().compareTo(arg1.toGenericString());
          }
        };
    Collections.sort(tokenizers, ctorComp);
    Collections.sort(tokenfilters, ctorComp);
    Collections.sort(charfilters, ctorComp);
    if (VERBOSE) {
      System.out.println("tokenizers = " + tokenizers);
      System.out.println("tokenfilters = " + tokenfilters);
      System.out.println("charfilters = " + charfilters);
    }
  }
package isola.helpers;
import isola.annotations.RemoteService;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javolution.util.FastMap;
/**
 * Utility class classloader related facilities for Isola Remote Services
 *
 * @author Umut Gokbayrak
 * @author Alisan Erdemli
 */
public class ClassLoaderHelper {
  private static FastMap<String, Object> remoteServices = new FastMap<String, Object>();
  private static List<String> omittedPackages = new ArrayList<String>();
  private static boolean initComplete = false;
  static {
    omittedPackages.add("com.sun.");
    omittedPackages.add("java.");
    omittedPackages.add("javax.");
    omittedPackages.add("org.ietf.");
    omittedPackages.add("org.jcp.");
    omittedPackages.add("org.omg.");
    omittedPackages.add("org.w3c.");
    omittedPackages.add("org.xml.");
    omittedPackages.add("sun.");
    omittedPackages.add("sunw.");
    omittedPackages.add("org.springframework.");
    omittedPackages.add("org.aspectj.");
    omittedPackages.add("org.mortbay.");
    omittedPackages.add("org.apache.");
    omittedPackages.add("freemarker.");
    omittedPackages.add("org.springframework.");
    omittedPackages.add("org.springframework.");
    omittedPackages.add("org.eclipse.");
  }
  public static List<Class<?>> getClassesForPackage(String pckgname) {
    List<Class<?>> classes = new ArrayList<Class<?>>();
    try {
      ClassLoader cld = Thread.currentThread().getContextClassLoader();
      if (cld == null) {
        throw new ClassNotFoundException("Can't get class loader.");
      }
      // Ask for all resources for the path
      Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
      while (resources.hasMoreElements()) {
        URL res = resources.nextElement();
        File f = new File(res.getFile());
        // if (f.exists()) {
        traverseRemoteServices(f, pckgname);
        // }
      }
    } catch (Throwable ex) {
      ex.printStackTrace();
    }
    return classes;
  }
  /**
   * Traverses the classpath and finds the classes annotating RemoteService
   *
   * <p>These are the classes with the remote serving capabilities. Puts them in a ArrayList
   * (static)
   *
   * @param packageName
   */
  public static void findRemoteServices(String packageName) {
    if (!initComplete) {
      try {
        List<Class<?>> classes = getClassesForPackage(packageName);
        if (classes != null) {
          for (int i = 0; i < classes.size(); i++) {
            try {
              Class<?> cls = classes.get(i);
              parseClass(cls);
            } catch (Throwable e) {
              e.printStackTrace();
            }
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      initComplete = true;
    }
  }
  /**
   * Recursive algorith to traverse the classpath.
   *
   * @param dir
   * @param packageName
   */
  private static void traverseRemoteServices(File dir, String packageName) {
    // check if the package is in the omitted list.
    for (int i = 0; i < omittedPackages.size(); i++) {
      if (packageName.startsWith(omittedPackages.get(i))) {
        return;
      }
    }
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        traverseRemoteServices(new File(dir, children[i]), packageName);
      }
    } else {
      if (dir.getName().endsWith(".class")) {
        try {
          String absPath = dir.getAbsolutePath().replace('\\', '/');
          String jPackageName = packageName.replace('.', '/');
          if (!jPackageName.startsWith("/")) {
            jPackageName = "/" + jPackageName;
          }
          if (absPath.indexOf(jPackageName) >= 0) {
            String className = dir.getName();
            className = className.substring(0, className.length() - 6);
            String pkgTmp =
                absPath.substring(
                    absPath.indexOf(jPackageName + "/") + 1, absPath.indexOf(dir.getName()) - 1);
            pkgTmp = pkgTmp.replace('/', '.');
            try {
              Class<?> oClass = Class.forName(pkgTmp + "." + className);
              parseClass(oClass);
              oClass = null;
            } catch (Throwable cnfex) {
              // System.err.println(cnfex);
            }
            className = null;
            className = null;
            pkgTmp = null;
          }
          absPath = null;
          jPackageName = null;
        } catch (Throwable e) {
          // e.printStackTrace();
        }
      } else if (dir.getName().endsWith(".jar") || dir.getAbsolutePath().indexOf(".jar!") > 0) {
        // Jar file.
        try {
          if (dir.getAbsolutePath().indexOf("!") > 0) {
            dir = new File(dir.getAbsolutePath().substring(0, dir.getAbsolutePath().indexOf("!")));
          }
          JarFile jfile = new JarFile(dir);
          Enumeration<JarEntry> e = jfile.entries();
          String jPackageName = packageName.replace('.', '/');
          if (!jPackageName.startsWith("/")) {
            jPackageName = "/" + jPackageName;
          }
          while (e.hasMoreElements()) {
            try {
              ZipEntry entry = e.nextElement();
              String entryName = entry.getName();
              entryName = entryName.replace('\\', '/');
              if (!entryName.startsWith("/")) {
                entryName = "/" + entryName;
              }
              if (entryName.indexOf(jPackageName) >= 0) {
                if (entryName.endsWith("class")) {
                  String className = entryName.substring(entryName.lastIndexOf("/") + 1);
                  String pkgTmp = entryName.substring(0, entryName.indexOf(className) - 1);
                  pkgTmp = pkgTmp.replace('/', '.');
                  if (pkgTmp.startsWith(".")) {
                    pkgTmp = pkgTmp.substring(1);
                  }
                  className = className.substring(0, className.length() - 6);
                  try {
                    Class<?> oClass = Class.forName(pkgTmp + "." + className);
                    parseClass(oClass);
                    oClass = null;
                  } catch (Throwable cnfex) {
                    // System.err.println(cnfex);
                  }
                  className = null;
                  pkgTmp = null;
                }
              }
              entry = null;
              entryName = null;
            } catch (Throwable e1) {
              e1.printStackTrace();
            }
          }
          jfile = null;
          e = null;
          jPackageName = null;
        } catch (Throwable ioex) {
          // System.err.println(ioex);
        }
      }
    }
  }
  /**
   * @param oClass
   * @throws Exception
   */
  private static void parseClass(Class<?> oClass) throws Exception {
    if (oClass.isAnnotationPresent(RemoteService.class)) {
      if (!oClass.isAnonymousClass() && !oClass.isInterface()) {
        Object o = oClass.newInstance();
        RemoteService rs = oClass.getAnnotation(RemoteService.class);
        if (rs.uri() != null && !rs.uri().equals("")) {
          remoteServices.put(rs.uri(), o);
        }
        o = null;
      }
    }
  }
  public static FastMap<String, Object> getRemoteServices() {
    return remoteServices;
  }
}
Example #26
0
 private boolean isAnonymousOrLocal(Class<?> clazz) {
   return !Enum.class.isAssignableFrom(clazz)
       && (clazz.isAnonymousClass() || clazz.isLocalClass());
 }
Example #27
0
  @Override
  public void beforeStart(final Application application) {
    final Reflections reflections =
        new Reflections(
            new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder.Exclude(FilterBuilder.prefix("com.google")))
                .addUrls(ClasspathHelper.forClassLoader(application.classloader()))
                .addScanners(new SubTypesScanner()));

    // automatic Guice module detection
    Set<Class<? extends AbstractModule>> guiceModules =
        reflections.getSubTypesOf(AbstractModule.class);
    for (Class<? extends Module> moduleClass : guiceModules) {
      try {
        if (!moduleClass.isAnonymousClass()) {
          modules.add(moduleClass.newInstance());
        }
      } catch (InstantiationException e) {
        throw Throwables.propagate(e);
      } catch (IllegalAccessException e) {
        throw Throwables.propagate(e);
      }
    }

    modules.add(
        new AbstractModule() {
          @Override
          protected void configure() {
            bind(Application.class).toInstance(application);
            bind(Reflections.class).toInstance(reflections);

            Names.bindProperties(
                this.binder(),
                fromKeys(
                    application.configuration().keys(),
                    new Function<String, String>() {
                      @Override
                      public String apply(String key) {
                        // remove after https://play.lighthouseapp.com/projects/82401/tickets/372 is
                        // fixed
                        if (key.contains("akka")) return null;

                        return application.configuration().getString(key);
                      }
                    }));

            for (Class<? extends Controller> controllerClass :
                reflections.getSubTypesOf(Controller.class)) {
              requestStaticInjection(controllerClass);
            }

            // bind all services
            Multibinder<Service> serviceBinder = Multibinder.newSetBinder(binder(), Service.class);
            for (Class<? extends Service> serviceImplClass :
                reflections.getSubTypesOf(AbstractService.class)) {
              serviceBinder.addBinding().to(serviceImplClass).asEagerSingleton();
            }
            for (Class<? extends Service> serviceImplClass :
                reflections.getSubTypesOf(AbstractIdleService.class)) {
              serviceBinder.addBinding().to(serviceImplClass).asEagerSingleton();
            }
            for (Class<? extends Service> serviceImplClass :
                reflections.getSubTypesOf(AbstractExecutionThreadService.class)) {
              serviceBinder.addBinding().to(serviceImplClass).asEagerSingleton();
            }

            // bind actor - todo use reflections for this

            // start/stop services after injection and on shutdown of the Play app
            bindListener(
                MoreMatchers.subclassesOf(Service.class),
                new TypeListener() {
                  @Override
                  public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
                    typeEncounter.register(
                        new InjectionListener<I>() {
                          @Override
                          public void afterInjection(final I i) {
                            onStartListeners.add(
                                new OnStartListener() {
                                  @Override
                                  public void onApplicationStart(
                                      Application application, Injector injector) {
                                    Logger.info(String.format("Starting %s", i.toString()));
                                    ((Service) i).start();

                                    onStopListeners.add(
                                        new OnStopListener() {
                                          @Override
                                          public void onApplicationStop(Application application) {
                                            Logger.info(String.format("Stopping %s", i.toString()));
                                            ((Service) i).stop();
                                          }
                                        });
                                  }
                                });
                          }
                        });
                  }
                });
          }
        });
  }
Example #28
0
 public static boolean isValidAnnotationBaseReturnType(Class cls) {
   // TODO review this calculation
   return (cls.isAnnotation() || cls.isEnum() || NamingUtils.isPrimitiveTypeId(cls.getName()))
       || (!cls.isAnonymousClass() && !cls.isLocalClass());
 }
  /** Immediately refreshes all types using the backing database. */
  public synchronized void refreshTypes() {
    bootstrapOnce.ensure();

    Database database = getDatabase();
    try {

      TypesCache temporaryTypes = temporaryTypesLocal.get();
      if (temporaryTypes == null) {
        temporaryTypes = new TypesCache();
        temporaryTypesLocal.set(temporaryTypes);
      }

      List<ObjectType> types = Query.from(ObjectType.class).using(database).selectAll();
      int typesSize = types.size();
      LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName());

      // Load all types from the database first.
      for (ObjectType type : types) {
        type.getFields().size(); // Pre-fetch.
        temporaryTypes.add(type);
      }

      if (initializeClasses) {

        // Make sure that the root type exists.
        ObjectType rootType = getRootType();
        State rootTypeState;

        if (rootType != null) {
          rootTypeState = rootType.getState();

        } else {
          rootType = new ObjectType();
          rootTypeState = rootType.getState();
          rootTypeState.setDatabase(database);
        }

        Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues();
        UUID rootTypeId = rootTypeState.getId();
        rootTypeState.setTypeId(rootTypeId);
        rootTypeState.clear();
        rootType.setObjectClassName(ObjectType.class.getName());
        rootType.initialize();
        temporaryTypes.add(rootType);

        try {
          database.beginWrites();

          // Make the new root type available to other types.
          temporaryTypes.add(rootType);
          if (rootTypeState.isNew()) {
            State globals = getGlobals();
            globals.put(ROOT_TYPE_FIELD, rootType);
            globals.save();

          } else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) {
            temporaryTypes.changed.add(rootTypeId);
          }

          Set<Class<? extends Recordable>> objectClasses =
              ClassFinder.findClasses(Recordable.class);

          for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) {
            Class<? extends Recordable> objectClass = i.next();

            try {
              if (objectClass.isAnonymousClass()
                  || Substitution.class.isAssignableFrom(objectClass)) {
                i.remove();
              }

            } catch (IncompatibleClassChangeError error) {
              i.remove();
            }
          }

          Set<Class<?>> globalModifications = new HashSet<Class<?>>();
          Map<ObjectType, List<Class<?>>> typeModifications =
              new HashMap<ObjectType, List<Class<?>>>();

          // Make sure all types are accessible to the rest of the
          // system as soon as possible, so that references can be
          // resolved properly later.
          for (Class<?> objectClass : objectClasses) {
            ObjectType type = getTypeByClass(objectClass);

            if (type == null) {
              type = new ObjectType();
              type.getState().setDatabase(database);

            } else {
              type.getState().clear();
            }

            type.setObjectClassName(objectClass.getName());
            typeModifications.put(type, new ArrayList<Class<?>>());
            temporaryTypes.add(type);
          }

          // Separate out all modifications from regular types.
          for (Class<?> objectClass : objectClasses) {
            if (!Modification.class.isAssignableFrom(objectClass)) {
              continue;
            }

            @SuppressWarnings("unchecked")
            Set<Class<?>> modifiedClasses =
                Modification.Static.getModifiedClasses(
                    (Class<? extends Modification<?>>) objectClass);
            if (modifiedClasses.contains(Object.class)) {
              globalModifications.add(objectClass);
              continue;
            }

            for (Class<?> modifiedClass : modifiedClasses) {
              List<Class<?>> assignableClasses = new ArrayList<Class<?>>();

              for (Class<?> c : objectClasses) {
                if (modifiedClass.isAssignableFrom(c)) {
                  assignableClasses.add(c);
                }
              }

              for (Class<?> assignableClass : assignableClasses) {
                ObjectType type = getTypeByClass(assignableClass);

                if (type != null) {
                  List<Class<?>> modifications = typeModifications.get(type);
                  if (modifications == null) {
                    modifications = new ArrayList<Class<?>>();
                    typeModifications.put(type, modifications);
                  }
                  modifications.add(objectClass);
                }
              }
            }
          }

          // Apply global modifications.
          for (Class<?> modification : globalModifications) {
            ObjectType.modifyAll(database, modification);
          }

          // Initialize all types.
          List<Class<?>> rootTypeModifications = typeModifications.remove(rootType);
          initializeAndModify(temporaryTypes, rootType, rootTypeModifications);

          if (rootTypeModifications != null) {
            for (Class<?> modification : rootTypeModifications) {
              ObjectType t = getTypeByClass(modification);
              initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
            }
          }

          ObjectType fieldType = getTypeByClass(ObjectField.class);
          List<Class<?>> fieldModifications = typeModifications.remove(fieldType);
          initializeAndModify(temporaryTypes, fieldType, fieldModifications);

          if (fieldModifications != null) {
            for (Class<?> modification : fieldModifications) {
              ObjectType t = getTypeByClass(modification);
              initializeAndModify(temporaryTypes, t, typeModifications.remove(t));
            }
          }

          for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) {
            initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue());
          }

          database.commitWrites();

        } finally {
          database.endWrites();
        }
      }

      // Merge temporary types into new permanent types.
      TypesCache newPermanentTypes = new TypesCache();

      for (ObjectType type : permanentTypes.byId.values()) {
        newPermanentTypes.add(type);
      }

      for (ObjectType type : temporaryTypes.byId.values()) {
        newPermanentTypes.add(type);
      }

      newPermanentTypes.changed.addAll(temporaryTypes.changed);
      newPermanentTypes.changed.addAll(permanentTypes.changed);

      // If any types changed, clear all types' extras.
      if (!temporaryTypes.changed.isEmpty()) {
        for (ObjectType type : newPermanentTypes.byId.values()) {
          type.getState().getExtras().clear();
        }
      }

      permanentTypes = newPermanentTypes;
      lastTypesUpdate = new Date();

    } finally {
      temporaryTypesLocal.remove();
    }

    ObjectType singletonType = getTypeByClass(Singleton.class);

    if (singletonType != null) {
      for (ObjectType type : singletonType.findConcreteTypes()) {
        if (!Query.fromType(type).where("_type = ?", type).master().noCache().hasMoreThan(0)) {
          try {
            State.getInstance(type.createObject(null)).saveImmediately();
          } catch (Exception error) {
            LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error);
          }
        }
      }
    }

    for (ObjectType type : getTypes()) {
      Class<?> objectClass = type.getObjectClass();
      if (objectClass != null) {
        TypePostProcessorClasses tppcAnnotation =
            objectClass.getAnnotation(TypePostProcessorClasses.class);
        if (tppcAnnotation != null) {
          for (Class<? extends ObjectType.PostProcessor> processorClass : tppcAnnotation.value()) {
            ObjectType.PostProcessor processor =
                (ObjectType.PostProcessor) TYPE_POST_PROCESSORS.getUnchecked(processorClass);
            processor.process(type);
          }
        }
      }
    }
  }
Example #30
0
 private boolean isInstanceOfRule(Class<?> ruleClass) {
   return ruleClass.getSimpleName().matches("^(.+Rule*)$")
       && !ruleClass.isAnonymousClass()
       && !ruleClass.isEnum()
       && ruleClass.getSuperclass().getName().equals(ruleTypeAbstractClass);
 }