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()); } }
@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(); } } }
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; }
/** * 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; }
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; }
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; }
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)); } }
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); } }
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); }
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()); }
@Override public String getIdPrefix() { Class<?> clazz = getClass(); if (clazz.isAnonymousClass()) { return "a"; } else { return clazz.getSimpleName().substring(0, 1); } }
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; } }
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)); }
/** * @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")); } } }
@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;
private boolean isAnonymousOrLocal(Class<?> clazz) { return !Enum.class.isAssignableFrom(clazz) && (clazz.isAnonymousClass() || clazz.isLocalClass()); }
@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(); } }); } }); } }); } }); } }); }
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); } } } } }
private boolean isInstanceOfRule(Class<?> ruleClass) { return ruleClass.getSimpleName().matches("^(.+Rule*)$") && !ruleClass.isAnonymousClass() && !ruleClass.isEnum() && ruleClass.getSuperclass().getName().equals(ruleTypeAbstractClass); }