/*
Class: AbstractComponent
Superclass for AbstractConnector and AbstractEndpoint.
186876
function () {
		this.resetBounds = function () {
			this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
		};
		this.resetBounds();
	}
1231569
public ClassDoc superclass() {
        if (isInterface() || isAnnotationType()) return null;
        if (tsym == env.syms.objectType.tsym) return null;
        ClassSymbol c = (ClassSymbol)env.types.supertype(type).tsym;
        if (c == null || c == tsym) c = (ClassSymbol)env.syms.objectType.tsym;
        return env.getClassDoc(c);
    }
21970
static OutputType getOutputComponentType(Class<? extends CommandOutput> commandOutputClass) {

        ClassTypeInformation<? extends CommandOutput> classTypeInformation = ClassTypeInformation.from(commandOutputClass);

        TypeInformation<?> superTypeInformation = classTypeInformation.getSuperTypeInformation(CommandOutput.class);

        if (superTypeInformation == null) {
            return null;
        }

        List<TypeInformation<?>> typeArguments = superTypeInformation.getTypeArguments();

        return new OutputType(commandOutputClass, typeArguments.get(2), false) {
            @Override
            public ResolvableType withCodec(RedisCodec<?, ?> codec) {

                TypeInformation<?> typeInformation = ClassTypeInformation.from(codec.getClass());

                ResolvableType resolvableType = ResolvableType.forType(commandOutputClass, new CodecVariableTypeResolver(
                        typeInformation));

                while (!resolvableType.getRawClass().equals(CommandOutput.class)) {
                    resolvableType = resolvableType.getSuperType();
                }

                return resolvableType.getGeneric(2);
            }
        };
    }
73898
public static <T extends Annotation> T getAnnotation(final Class<?> componentClass,
		final Class<T> annotationClass)
	{
		T annotation = componentClass.getAnnotation(annotationClass);
		if (annotation != null)
		{
			return annotation;
		}
		for (final Class<?> ifc : componentClass.getInterfaces())
		{
			annotation = getAnnotation(ifc, annotationClass);
			if (annotation != null)
			{
				return annotation;
			}
		}
		if (!Annotation.class.isAssignableFrom(componentClass))
		{
			for (final Annotation ann : componentClass.getAnnotations())
			{
				annotation = getAnnotation(ann.annotationType(), annotationClass);
				if (annotation != null)
				{
					return annotation;
				}
			}
		}
		final Class<?> superClass = componentClass.getSuperclass();
		if (superClass == null || superClass.equals(Object.class))
		{
			return null;
		}
		return getAnnotation(superClass, annotationClass);
	}
160967
private void appendSuperClassJoin(ClassDescriptor cld, ClassDescriptor cldSuper, StringBuffer stmt, StringBuffer where)
    {
        stmt.append(",");
        appendTable(cldSuper, stmt);

        if (where != null)
        {
            if (where.length() > 0)
            {
                where.append(" AND ");
            }

            // get reference field in super class
            // TODO: do not use the superclassfield anymore, just assume that the id is the same in both tables - @see PBroker.storeToDb
            int superFieldRef = cld.getSuperClassFieldRef();
            FieldDescriptor refField = cld.getFieldDescriptorByIndex(superFieldRef);

            appendTable(cldSuper, where);
            where.append(".");
            appendField(cldSuper.getAutoIncrementFields()[0], where);
            where.append(" = ");
            appendTable(cld, where);
            where.append(".");
            appendField(refField, where);
        }
    }
339792
@Nullable
	public static <T> InterfaceDescriptor<T> findInterfaceDescriptor(final Class<T> cls) {
		if (!cls.isInterface()) {
			throw new IllegalArgumentException("Interface required, got " + cls);
		}

		Field field;
		try {
			field = cls.getField("DESCRIPTOR");
		} catch (NoSuchFieldException e) {
			throw new IllegalArgumentException("No DESCRIPTOR field in " + cls);
		}

		if (!InterfaceDescriptor.class.isAssignableFrom(field.getType())) {
			throw new IllegalArgumentException("Not an InterfaceDescriptor field, " + field);
		}

		try {
			// Get the static TYPE field.
			@SuppressWarnings("unchecked")
			InterfaceDescriptor<T> descriptor = (InterfaceDescriptor<T>) field.get(null);
			return descriptor;
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
501465
private static Class<? extends ServerChannel> epollServerChannelType() {
    try {
      Class<? extends ServerChannel> serverSocketChannel =
          Class
              .forName("io.netty.channel.epoll.EpollServerSocketChannel")
              .asSubclass(ServerChannel.class);
      return serverSocketChannel;
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Cannot load EpollServerSocketChannel", e);
    }
  }
841357
private void findLocalComponentsForComponent(LocalComponents localComponents,
      TypeElement componentTypeElement) {
    Component componentAnnotation = componentTypeElement.getAnnotation(Component.class);
    if (componentAnnotation == null) {
      return;
    }

    processLocalComponentClass(localComponents, componentTypeElement);
    getComponentLocalComponents(elements, componentTypeElement)
        .stream()
        .map(DeclaredType.class::cast)
        .map(DeclaredType::asElement)
        .map(TypeElement.class::cast)
        .forEach(childTypeElement -> processLocalComponentClass(localComponents,
            childTypeElement));

    getSuperComponentType(componentTypeElement)
        .ifPresent(superComponentType -> findLocalComponentsForComponent(
            localComponents,
            superComponentType));
  }
955150
public ProxyBuilder<T> withInterface(Class<?> interfaceClass, Object interfaceImpl) {
    this.interfacesToImplementations.put(interfaceClass, interfaceImpl);
    return this;
  }
353311
function(cls,superClass) {
    superClass = lib.resolve.resolve(superClass);
    factory.inherits(cls,superClass);
  }
1176133
protected <E extends Event> void subscribeEvent(Class<E> eventClass, final Listener<E> listener) {
        locator.inject(listener);
        locator.postConstruct(listener);
        subscribe(eventClass, listener);
    }
479425
public void createChildAccessors(ClassIndex index, ClassPlan plan, JavaClassSource javaClass) {

        Inflector inflector = new Inflector();

        ResourceMetaData resourceMetaData = plan.getMetaData();

        final JavaClassSource subresourceClass = getOrCreateSubresourceClass(plan, javaClass);

        // For each subresource create a getter/mutator/list-mutator
        final ResourceDescription resourceMetaDataDescription = resourceMetaData.getDescription();
        final Set<String> childrenNames = resourceMetaDataDescription.getChildrenTypes();
        for (String childName : childrenNames) {
            this.names.add(childName);

            final AddressTemplate childAddress = resourceMetaData.getAddress().append(childName + "=*");
            final ClassPlan childClass = index.lookup(childAddress);
            //javaClass.addImport(childClass);

            javaClass.addImport(childClass.getFullyQualifiedClassName() + "Consumer");
            javaClass.addImport(childClass.getFullyQualifiedClassName() + "Supplier");

            final String childClassName = childClass.getClassName();
            javaClass.addImport(childClass.getFullyQualifiedClassName());
            final String propType = "java.util.List<" + childClassName + ">";
            String propName = CaseFormat.UPPER_CAMEL.to(
                    CaseFormat.LOWER_CAMEL,
                    Keywords.escape(childClass.getOriginalClassName())
            );

            String singularName = propName;
            String pluralName = inflector.pluralize(singularName);

            if (!propName.endsWith("s")) {
                propName = pluralName;
            }


            javaClass.addImport(SubresourceInfo.class);

            // Add a property and an initializer for this subresource to the class
            final String resourceText = resourceMetaDataDescription.getChildDescription(childName).getText();
            FieldSource<JavaClassSource> field = subresourceClass.addField();

            field.setName(propName)
                    .setType(propType)
                    .setPrivate()
                    .setLiteralInitializer("new java.util.ArrayList<>();")
                    .getJavaDoc().setText(resourceText);

            AnnotationSource attributeAnnotation = field.addAnnotation();
            attributeAnnotation.setName(ResourceDocumentation.class.getSimpleName());
            attributeAnnotation.setStringValue(resourceText);

            field.addAnnotation(SubresourceInfo.class).setStringValue(singularName);

            // Add an accessor method
            final MethodSource<JavaClassSource> accessor = subresourceClass.addMethod();
            accessor.getJavaDoc()
                    .setText("Get the list of " + childClassName + " resources")
                    .addTagValue("@return", "the list of resources");
            accessor.setPublic()
                    .setName(propName)
                    .setReturnType(propType)
                    .setBody("return this." + propName + ";");

            final MethodSource<JavaClassSource> getByKey = subresourceClass.addMethod();
            getByKey.addParameter(String.class, "key");
            getByKey.setPublic()
                    .setName(singularName)
                    .setReturnType(childClassName)
                    .setBody("return this." + propName + ".stream().filter( e->e.getKey().equals(key) ).findFirst().orElse(null);");

            // Add a mutator method that takes a list of resources. Mutators are added to the containing class
            final MethodSource<JavaClassSource> listMutator = javaClass.addMethod();
            listMutator.getJavaDoc()
                    .setText("Add all " + childClassName + " objects to this subresource")
                    .addTagValue("@return", "this")
                    .addTagValue("@param", "value List of " + childClassName + " objects.");
            listMutator.addParameter(propType, "value");
            listMutator.setPublic()
                    .setName(propName)
                    .setReturnType("T")
                    .setBody("this.subresources." + propName + " = value;\nreturn (T) this;")
                    .addAnnotation("SuppressWarnings").setStringValue("unchecked");

            // Add a mutator method that takes a single resource. Mutators are added to the containing class
            final MethodSource<JavaClassSource> mutator = javaClass.addMethod();
            mutator.getJavaDoc()
                    .setText("Add the " + childClassName + " object to the list of subresources")
                    .addTagValue("@param", "value The " + childClassName + " to add")
                    .addTagValue("@return", "this");
            mutator.addParameter(childClassName, "value");
            mutator.setPublic()
                    .setName(singularName)
                    .setReturnType("T")
                    .setBody("this.subresources." + propName + ".add(value);\nreturn (T) this;")
                    .addAnnotation("SuppressWarnings").setStringValue("unchecked");

            // Add a mutator method that factories a single resource and applies a supplied configurator. Mutators are added to the containing class
            final MethodSource<JavaClassSource> configurator = javaClass.addMethod();
            configurator.getJavaDoc()
                    .setText("Create and configure a " + childClassName + " object to the list of subresources")
                    .addTagValue("@param", "key The key for the " + childClassName + " resource")
                    .addTagValue("@param", "config The " + childClassName + "Consumer to use")
                    .addTagValue("@return", "this");
            configurator.addParameter(String.class, "childKey");
            configurator.addParameter(childClassName + "Consumer", "consumer");
            //configurator.addParameter(childClassName + "Consumer", "consumer");
            configurator.setPublic()
                    .setName(singularName)
                    .setReturnType("T")
                    .setBody(childClassName + "<? extends " + childClassName + "> child = new " + childClassName + "<>(childKey);\n if ( consumer != null ) { consumer.accept(child); }\n" + singularName + "(child);\nreturn (T) this;")
                    .addAnnotation("SuppressWarnings").setStringValue("unchecked");

            // Add a mutator method that factories a single resource and applies a supplied configurator. Mutators are added to the containing class
            final MethodSource<JavaClassSource> nonConfigurator = javaClass.addMethod();
            nonConfigurator.getJavaDoc()
                    .setText("Create and configure a " + childClassName + " object to the list of subresources")
                    .addTagValue("@param", "key The key for the " + childClassName + " resource")
                    .addTagValue("@return", "this");
            nonConfigurator.addParameter(String.class, "childKey");
            nonConfigurator.setPublic()
                    .setName(singularName)
                    .setReturnType("T")
                    .setBody(singularName + "(childKey, null);\nreturn (T) this;\n")
                    .addAnnotation("SuppressWarnings").setStringValue("unchecked");


            // Add a supplier to create

            final MethodSource<JavaClassSource> supplier = javaClass.addMethod();
            supplier.getJavaDoc()
                    .setText("Install a supplied " + childClassName + " object to the list of subresources");
            //supplier.addParameter(childClassName + "Supplier", "supplier");
            supplier.addParameter(childClassName + "Supplier", "supplier");
            supplier.setPublic()
                    .setName(singularName)
                    .setReturnType("T")
                    .setBody(singularName + "(supplier.get()); return (T) this;")
                    .addAnnotation("SuppressWarnings").setStringValue("unchecked");

            final AnnotationSource<JavaClassSource> subresourceMeta = accessor.addAnnotation();
            subresourceMeta.setName("Subresource");


        }

        // initialize the collections
    }
1150478
private static Class<? extends OrmLiteSqliteOpenHelper> lookupHelperClass(Context context, Class<?> componentClass) {

		// see if we have the magic resource class name set
		Resources resources = context.getResources();
		int resourceId = resources.getIdentifier(HELPER_CLASS_RESOURCE_NAME, "string", context.getPackageName());
		if (resourceId != 0) {
			String className = resources.getString(resourceId);
			try {
				@SuppressWarnings("unchecked")
				Class<? extends OrmLiteSqliteOpenHelper> castClass =
						(Class<? extends OrmLiteSqliteOpenHelper>) Class.forName(className);
				return castClass;
			} catch (Exception e) {
				throw new IllegalStateException("Could not create helper instance for class " + className, e);
			}
		}

		// try walking the context class to see if we can get the OrmLiteSqliteOpenHelper from a generic parameter
		for (Class<?> componentClassWalk = componentClass; componentClassWalk != null; componentClassWalk =
				componentClassWalk.getSuperclass()) {
			Type superType = componentClassWalk.getGenericSuperclass();
			if (superType == null || !(superType instanceof ParameterizedType)) {
				continue;
			}
			// get the generic type arguments
			Type[] types = ((ParameterizedType) superType).getActualTypeArguments();
			// defense
			if (types == null || types.length == 0) {
				continue;
			}
			for (Type type : types) {
				// defense
				if (!(type instanceof Class)) {
					continue;
				}
				Class<?> clazz = (Class<?>) type;
				if (OrmLiteSqliteOpenHelper.class.isAssignableFrom(clazz)) {
					@SuppressWarnings("unchecked")
					Class<? extends OrmLiteSqliteOpenHelper> castOpenHelperClass =
							(Class<? extends OrmLiteSqliteOpenHelper>) clazz;
					return castOpenHelperClass;
				}
			}
		}
		throw new IllegalStateException(
				"Could not find OpenHelperClass because none of the generic parameters of class " + componentClass
						+ " extends OrmLiteSqliteOpenHelper.  You should use getHelper(Context, Class) instead.");
	}
143666
public void setIndirectionHandlerClass(Class indirectionHandlerClass)
    {
        if(indirectionHandlerClass == null)
        {
            //throw new MetadataException("No IndirectionHandlerClass specified.");
            /**
             * andrew.clute
             * Allow the default IndirectionHandler for the given ProxyFactory implementation
             * when the parameter is not given
             */
            indirectionHandlerClass = getDefaultIndirectionHandlerClass();
        }
        if(indirectionHandlerClass.isInterface()
                || Modifier.isAbstract(indirectionHandlerClass.getModifiers())
                || !getIndirectionHandlerBaseClass().isAssignableFrom(indirectionHandlerClass))
        {
            throw new MetadataException("Illegal class "
                    + indirectionHandlerClass.getName()
                    + " specified for IndirectionHandlerClass. Must be a concrete subclass of "
                    + getIndirectionHandlerBaseClass().getName());
        }
        _indirectionHandlerClass = indirectionHandlerClass;
    }
768878
@SuppressWarnings("unchecked")
	 Class<?>[] getAllInterfacesAndClasses ( Class<?>[] classes ) 
    {
        if(0 == classes.length ) 
        {
            return classes;
        }
        else 
        {
            List<Class<?>> extendedClasses = new ArrayList<Class<?>>();
            // all interfaces hierarchy
            for (Class<?> clazz: classes) {
            	if (clazz != null) 
            	{
            		Class<?>[] interfaces = clazz.getInterfaces();
	                if (interfaces != null)
	                {
	                	extendedClasses.addAll(Arrays.asList(interfaces));
	                }
	                Class<?> superclass = clazz.getSuperclass();
	                if (superclass != null && superclass != Object.class)
	                {
	                	extendedClasses.addAll(Arrays.asList(superclass));
	                }
            	}
            }
            
            //Class::getInterfaces() gets only interfaces/classes implemented/extended directly by a given class.
            //We need to walk the whole way up the tree.
            return (Class[]) ArrayUtils.addAll( classes, getAllInterfacesAndClasses( extendedClasses.toArray(new Class[extendedClasses.size()])));
        }
    }
615517
@Override
    public Set<Class<?>> getComponents() {
        Set<Class<?>> set = new HashSet<>();
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        Consumer<JsonArray> reader = array -> {
            if (array != null && array.size() > 0) {
                for (int i = 0; i < array.size(); i++) {
                    try {
                        set.add(cl.loadClass(array.getString(i)));
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };

        JsonArray features = config.getJsonArray(CONFIG_FEATURES, null);
        JsonArray components = config.getJsonArray(CONFIG_COMPONENTS, null);

        reader.accept(features);
        reader.accept(components);

        return set;
    }
228651
@Nullable
  public static XComponent getCurrentComponent(XComponentContext xContext) {
    try {
      XDesktop xdesktop = getCurrentDesktop(xContext);
      if(xdesktop == null) {
        return null;
      }
      else return xdesktop.getCurrentComponent();
    } catch (Throwable t) {
      MessageHandler.printException(t);     // all Exceptions thrown by UnoRuntime.queryInterface are caught
      return null;           // Return null as method failed
    }
  }