private <T extends View> T instanceView(Class<T> view) { if (view.isAssignableFrom(JSONSerialization.class)) { serialization = new GsonJSONSerialization( response, extractor, gsonBuilder, environment, reflectionProvider); return view.cast(serialization); } if (view.isAssignableFrom(XMLSerialization.class)) { serialization = new XStreamXMLSerialization(response, xstreambuilder, environment); return view.cast(serialization); } if (view.isAssignableFrom(RepresentationResult.class)) { serialization = new XStreamXMLSerialization(response, xstreambuilder, environment); return view.cast( new DefaultRepresentationResult( new FormatResolver() { @Override public String getAcceptFormat() { return "xml"; } }, this, new MockInstanceImpl<>(this.serialization))); } return proxifier.proxify(view, returnOnFinalMethods(view)); }
/** * Returns the generic supertype for {@code supertype}. For example, given a class {@code * IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the * result when the supertype is {@code Collection.class} is {@code Collection<Integer>}. */ static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) { if (toResolve == rawType) { return context; } // we skip searching through interfaces if unknown is an interface if (toResolve.isInterface()) { Class<?>[] interfaces = rawType.getInterfaces(); for (int i = 0, length = interfaces.length; i < length; i++) { if (interfaces[i] == toResolve) { return rawType.getGenericInterfaces()[i]; } else if (toResolve.isAssignableFrom(interfaces[i])) { return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve); } } } // check our supertypes if (!rawType.isInterface()) { while (rawType != Object.class) { Class<?> rawSupertype = rawType.getSuperclass(); if (rawSupertype == toResolve) { return rawType.getGenericSuperclass(); } else if (toResolve.isAssignableFrom(rawSupertype)) { return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve); } rawType = rawSupertype; } } // we can't resolve this further return toResolve; }
/** * Method description * * @param ht_def_key * @param ht_dev_val * @param st_def_key * @param st_def_val * @param prop_key * @param prop_val_class * @param params * @param props * @param <T> */ protected <T> void checkHighThroughputProperty( String ht_def_key, T ht_dev_val, String st_def_key, T st_def_val, String prop_key, Class<T> prop_val_class, Map<String, Object> params, Map<String, Object> props) { T tmp = st_def_val; String str_tmp = null; if (isHighThroughput()) { tmp = ht_dev_val; str_tmp = (String) params.get(ht_def_key); } else { tmp = st_def_val; str_tmp = (String) params.get(st_def_key); } if (prop_val_class.isAssignableFrom(Integer.class)) { tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Integer.class, (Integer) tmp)); } if (prop_val_class.isAssignableFrom(Long.class)) { tmp = prop_val_class.cast(DataTypes.parseNum(str_tmp, Long.class, (Long) tmp)); } if (prop_val_class.isAssignableFrom(String.class)) { tmp = prop_val_class.cast(str_tmp); } props.put(prop_key, tmp); }
private static boolean verifyReturn(Class columnClass, Class returnType) { if (columnClass.isAssignableFrom(returnType)) return true; if (returnType.isPrimitive()) { return (columnClass.isAssignableFrom(getWrapper(returnType))); } return false; }
/** * Gets the producers for the closest super class of the target class * * @param targetClass The target class * @return The producer */ protected ContentProducer getSuperClassContentProducer(Class targetClass, Class closestClass) { Map.Entry entry; Class entryClass; ContentProducer closestProducer = null; Iterator iter = fContentProducers.entrySet().iterator(); while (iter.hasNext()) { entry = (Map.Entry) iter.next(); entryClass = (Class) entry.getKey(); if (entryClass.isAssignableFrom(targetClass)) { if (closestClass != null && closestClass.isAssignableFrom(entryClass)) { closestClass = entryClass; closestProducer = (ContentProducer) entry.getValue(); } } } // whether we found one or not ask our parent to see if a more // exact producer is defined // unless we are autonomous (ie: we have no parent) if (!this.isAutonomous()) { ContentProducer parentProducer = getParent().getSuperClassContentProducer(targetClass, closestClass); if (parentProducer != null) { closestProducer = parentProducer; } } return closestProducer; }
public static long[] getLongValues(Object value, long[] defaultValue) { Class<?> clazz = value.getClass(); if (clazz.isArray()) { Class<?> componentType = clazz.getComponentType(); if (componentType.isAssignableFrom(String.class)) { return getLongValues((String[]) value, defaultValue); } else if (componentType.isAssignableFrom(Long.class)) { return (long[]) value; } else if (Number.class.isAssignableFrom(componentType)) { Number[] numbers = (Number[]) value; long[] values = new long[numbers.length]; for (int i = 0; i < values.length; i++) { values[i] = numbers[i].longValue(); } return values; } } return defaultValue; }
/** * @param geoclass * @return */ protected Feature createBasicFeature(Class<? extends Geometry> geoclass) { Feature f = new Feature(); count.incrementAndGet(); f.setName("feature" + count); f.setDescription("feature description " + count); if (geoclass.isAssignableFrom(Point.class)) { Point p = new Point(new Geodetic2DPoint(random)); f.setGeometry(p); } else if (geoclass.isAssignableFrom(Line.class)) { List<Point> pts = new ArrayList<Point>(); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); f.setGeometry(new Line(pts)); } else if (geoclass.isAssignableFrom(LinearRing.class)) { List<Point> pts = new ArrayList<Point>(); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); f.setGeometry(new LinearRing(pts)); } else if (geoclass.isAssignableFrom(Polygon.class)) { List<Point> pts = new ArrayList<Point>(); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); pts.add(new Point(new Geodetic2DPoint(random))); f.setGeometry(new Polygon(new LinearRing(pts))); } return f; }
/** * Creates a {@link WritableRaster writable raster}. * * @param width width of the raster to create. * @param height height of the raster to create. * @param dataClass data type for the raster. If <code>null</code>, defaults to double. * @param sampleModel the samplemodel to use. If <code>null</code>, defaults to <code> * new ComponentSampleModel(dataType, width, height, 1, width, new int[]{0});</code>. * @param value value to which to set the raster to. If null, the default of the raster creation * is used, which is 0. * @return a {@link WritableRaster writable raster}. */ public static WritableRaster createDoubleWritableRaster( int width, int height, Class<?> dataClass, SampleModel sampleModel, Double value) { int dataType = DataBuffer.TYPE_DOUBLE; if (dataClass != null) { if (dataClass.isAssignableFrom(Integer.class)) { dataType = DataBuffer.TYPE_INT; } else if (dataClass.isAssignableFrom(Float.class)) { dataType = DataBuffer.TYPE_FLOAT; } else if (dataClass.isAssignableFrom(Byte.class)) { dataType = DataBuffer.TYPE_BYTE; } } if (sampleModel == null) { sampleModel = new ComponentSampleModel(dataType, width, height, 1, width, new int[] {0}); } WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, null); if (value != null) { // autobox only once double v = value; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { raster.setSample(x, y, 0, v); } } } return raster; }
/** * Tests whether or not the left hand type is compatible with the right hand type in Groovy terms, * i.e. can the left type be assigned a value of the right hand type in Groovy. * * <p>This handles Java primitive type equivalence and uses isAssignableFrom for all other types, * with a bit of magic for native types and polymorphism i.e. Number assigned an int. If either * parameter is null an exception is thrown * * @param leftType The type of the left hand part of a notional assignment * @param rightType The type of the right hand part of a notional assignment * @return true if values of the right hand type can be assigned in Groovy to variables of the * left hand type. */ public static boolean isGroovyAssignableFrom(Class<?> leftType, Class<?> rightType) { if (leftType == null) { throw new NullPointerException("Left type is null!"); } if (rightType == null) { throw new NullPointerException("Right type is null!"); } if (leftType == Object.class) { return true; } if (leftType == rightType) { return true; } // check for primitive type equivalence Class<?> r = PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(leftType); boolean result = r == rightType; if (!result) { // If no primitive <-> wrapper match, it may still be assignable // from polymorphic primitives i.e. Number -> int (AKA Integer) if (rightType.isPrimitive()) { // see if incompatible r = PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(rightType); if (r != null) { result = leftType.isAssignableFrom(r); } } else { // Otherwise it may just be assignable using normal Java polymorphism result = leftType.isAssignableFrom(rightType); } } return result; }
/** * @param source the (annotation) origin * @param ignore the set of {@link Throwable}s to reduce (if subsumed) * @return */ @SafeVarargs public static Set<Class<? extends Throwable>> subsume( final String source, final Class<? extends Throwable>... ignore) { final Set<Class<? extends Throwable>> result = new HashSet<>(); if (ignore != null && ignore.length != 0) outer: for (Class<? extends Throwable> cls : ignore) { for (Class<? extends Throwable> old : result) { if (old.isAssignableFrom(cls)) { LOG.info( "ignore() level '" + old.getName() + "' subsumes '" + cls.getName() + "' annotated in " + source); continue outer; } if (cls.isAssignableFrom(old)) { LOG.info( "ignore() level '" + cls.getName() + "' annotated in " + source + " subsumes '" + old.getName() + "'"); result.remove(old); } } result.add(cls); } return result; }
/** * note that we must have {@code multiModuleClass} <: {@code moduleClass}, which means that the * moduleClass is a supertype of multiModuleClass. * * @param moduleClass * @param multiModuleClass * @param addMethod(multiModule, childModule) will add the childModule to the superModule */ public ModuleFactory( Class<T> moduleClass, Class<? extends T> multiModuleClass, BiConsumer<T, T> addMethod) { this.moduleClass = moduleClass; this.multiModuleClass = multiModuleClass; this.addMethod = addMethod; // verifies that the classes are the correct type in our tree. Function<NTree<Class<?>>, Class<?>> verifyFn = NTree.traverseUp( (L, l) -> { if (!(L.isEmpty() || multiModuleClass.isAssignableFrom(l))) { reflectError( "Parent " + l + " is not an instance of specified multi module class " + this.multiModuleClass); } return l; }, (Class<?> l) -> { if (!moduleClass.isAssignableFrom(l)) { reflectError( "Child " + l + " is not an instance of specified module class " + moduleClass); } return l; }); if (!moduleClass.isAssignableFrom(multiModuleClass)) { reflectError( "MultiModule class " + multiModuleClass + " does not extend module class " + moduleClass); } // add this verification addVerification(verifyFn::apply); }
public int conversionPreference(Class javaClass) { if (javaClass.isAssignableFrom(DateValue.class)) return 0; if (javaClass.isAssignableFrom(XMLGregorianCalendar.class)) return 1; if (javaClass.isAssignableFrom(GregorianCalendar.class)) return 2; if (javaClass == Date.class) return 3; return Integer.MAX_VALUE; }
boolean isAssignable(Method m1, Method m2) { if (m1 == null) { return true; // choose second method } if (m2 == null) { return false; // choose first method } if (!m1.getName().equals(m2.getName())) { return true; // choose second method by default } Class<?> type1 = m1.getDeclaringClass(); Class<?> type2 = m2.getDeclaringClass(); if (!type1.isAssignableFrom(type2)) { return false; // choose first method: it declared later } type1 = getReturnType(getClass0(), m1); type2 = getReturnType(getClass0(), m2); if (!type1.isAssignableFrom(type2)) { return false; // choose first method: it overrides return type } Class<?>[] args1 = getParameterTypes(getClass0(), m1); Class<?>[] args2 = getParameterTypes(getClass0(), m2); if (args1.length != args2.length) { return true; // choose second method by default } for (int i = 0; i < args1.length; i++) { if (!args1[i].isAssignableFrom(args2[i])) { return false; // choose first method: it overrides parameter } } return true; // choose second method }
@SuppressWarnings("unchecked") public List<T> getSelectedTrainings(final List<?> objects) { final List<T> trainings = new ArrayList<>(); for (final Object obj : objects) { if (obj instanceof Integer) { final DateTime von = new DateTime((int) obj, 1, 1, 0, 0); final DateTime bis = new DateTime((int) obj, 12, 31, 23, 59); if (type.isAssignableFrom(ITraining.class)) { trainings.addAll( (Collection<? extends T>) databaseAccess.getTrainingsByAthleteAndDate(athlete, von, bis)); } } if (obj instanceof INavigationParent) { final INavigationParent parent = (INavigationParent) obj; final List<INavigationItem> childs = parent.getChilds(); for (final INavigationItem child : childs) { if (type.isAssignableFrom(child.getClass())) { trainings.add(((T) child)); } } } if (type.isAssignableFrom(obj.getClass())) { trainings.add((T) obj); } } return trainings; }
static <C extends Collection<?>, E> Collection<E> createCollection( Class<C> collectionType, Collection<? extends E> elements) throws IllegalAccessException, InstantiationException { final Collection<E> result; // If the collectionType is Abstract (or an Interface) we try to guess a valid // implementation... if (Modifier.isAbstract(collectionType.getModifiers())) { // FIXME: Maybe we should add some more implementations here? if (collectionType.isAssignableFrom(HashSet.class)) { result = new HashSet<E>(); } else if (collectionType.isAssignableFrom(LinkedList.class)) { result = new LinkedList<E>(); } else { throw new InstantiationException( "Could not find an implementation of " + collectionType.getName()); } } else { result = createInstance(collectionType); } if (elements != null) { result.addAll(elements); } return result; }
// ----- protected methods ----- protected Direction getDirectionForType( final Class<S> sourceType, final Class<T> targetType, final Class<? extends NodeInterface> type) { if (sourceType.equals(type) && targetType.equals(type)) { return Direction.BOTH; } if (sourceType.equals(type)) { return Direction.OUTGOING; } if (targetType.equals(type)) { return Direction.INCOMING; } if (sourceType.isAssignableFrom(type)) { return Direction.OUTGOING; } if (targetType.isAssignableFrom(type)) { return Direction.INCOMING; } return Direction.BOTH; }
private Collection createCollection(Type type) { Class<?> rawClass = getRawClass(type); Collection list; if (rawClass == AbstractCollection.class) { list = new ArrayList(); } else if (rawClass.isAssignableFrom(HashSet.class)) { list = new HashSet(); } else if (rawClass.isAssignableFrom(LinkedHashSet.class)) { list = new LinkedHashSet(); } else if (rawClass.isAssignableFrom(TreeSet.class)) { list = new TreeSet(); } else if (rawClass.isAssignableFrom(ArrayList.class)) { list = new ArrayList(); } else if (rawClass.isAssignableFrom(EnumSet.class)) { Type itemType; if (type instanceof ParameterizedType) { itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; } else { itemType = Object.class; } list = EnumSet.noneOf((Class<Enum>) itemType); } else { try { list = (Collection) rawClass.newInstance(); } catch (Exception e) { throw new PropertiesConfigurationResolveException( "create instance error, class " + rawClass.getName()); } } return list; }
@SuppressWarnings("unchecked") public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) { DataType type = metadata.getType(i); if (type.getName() != DataType.Name.MAP) throw new InvalidTypeException( String.format("Column %s is not of map type", metadata.getName(i))); Class<?> expectedKeysClass = type.getTypeArguments().get(0).getName().javaType; Class<?> expectedValuesClass = type.getTypeArguments().get(1).getName().javaType; if (!keysClass.isAssignableFrom(expectedKeysClass) || !valuesClass.isAssignableFrom(expectedValuesClass)) throw new InvalidTypeException( String.format( "Column %s is a map of %s->%s (CQL type %s), cannot be retrieve as a map of %s->%s", metadata.getName(i), expectedKeysClass, expectedValuesClass, type, keysClass, valuesClass)); ByteBuffer value = data.get(i); if (value == null) return Collections.<K, V>emptyMap(); return Collections.unmodifiableMap(Codec.<Map<K, V>>getCodec(type).compose(value)); }
protected static boolean isArgumentSupported(String typeName) { Class<?> type = toClass(typeName); if (type.isArray()) { return false; } if (type.isPrimitive()) { return true; } if (type.isAssignableFrom(Boolean.class)) { return true; } if (type.isAssignableFrom(Number.class)) { return true; } if (type.isAssignableFrom(Character.class)) { return true; } if (type.isAssignableFrom(String.class)) { return true; } return false; }
public JsonDeserializer<?> findDeserializer( JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { final Class<?> rawType = type.getRawClass(); if (_jdk7Helper != null) { JsonDeserializer<?> deser = _jdk7Helper.getDeserializerForJavaNioFilePath(rawType); if (deser != null) { return deser; } } if ((CLASS_DOM_NODE != null) && CLASS_DOM_NODE.isAssignableFrom(rawType)) { return (JsonDeserializer<?>) instantiate(DESERIALIZER_FOR_DOM_NODE); } if ((CLASS_DOM_DOCUMENT != null) && CLASS_DOM_DOCUMENT.isAssignableFrom(rawType)) { return (JsonDeserializer<?>) instantiate(DESERIALIZER_FOR_DOM_DOCUMENT); } String className = rawType.getName(); String factoryName; if (className.startsWith(PACKAGE_PREFIX_JAVAX_XML) || hasSuperClassStartingWith(rawType, PACKAGE_PREFIX_JAVAX_XML)) { factoryName = DESERIALIZERS_FOR_JAVAX_XML; } else { return null; } Object ob = instantiate(factoryName); if (ob == null) { // could warn, if we had logging system (j.u.l?) return null; } return ((Deserializers) ob).findBeanDeserializer(type, config, beanDesc); }
@Override protected <T> T internalValueOfString( final String value, final EdmLiteralKind literalKind, final EdmFacets facets, final Class<T> returnType) throws EdmSimpleTypeException { Calendar valueCalendar; if (literalKind == EdmLiteralKind.URI) { if (value.length() > 6 && value.startsWith("time'") && value.endsWith("'")) { valueCalendar = parseLiteral(value.substring(5, value.length() - 1), facets); } else { throw new EdmSimpleTypeException( EdmSimpleTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value)); } } else { valueCalendar = parseLiteral(value, facets); } if (returnType.isAssignableFrom(Calendar.class)) { return returnType.cast(valueCalendar); } else if (returnType.isAssignableFrom(Long.class)) { return returnType.cast(valueCalendar.getTimeInMillis()); } else if (returnType.isAssignableFrom(Date.class)) { return returnType.cast(valueCalendar.getTime()); } else { throw new EdmSimpleTypeException( EdmSimpleTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType)); } }
public JsonSerializer<?> findSerializer( SerializationConfig config, JavaType type, BeanDescription beanDesc) { final Class<?> rawType = type.getRawClass(); if (_jdk7Helper != null) { Class<?> path = _jdk7Helper.getClassJavaNioFilePath(); if (path.isAssignableFrom(rawType)) { return ToStringSerializer.instance; } } if ((CLASS_DOM_NODE != null) && CLASS_DOM_NODE.isAssignableFrom(rawType)) { return (JsonSerializer<?>) instantiate(SERIALIZER_FOR_DOM_NODE); } String className = rawType.getName(); String factoryName; if (className.startsWith(PACKAGE_PREFIX_JAVAX_XML) || hasSuperClassStartingWith(rawType, PACKAGE_PREFIX_JAVAX_XML)) { factoryName = SERIALIZERS_FOR_JAVAX_XML; } else { return null; } Object ob = instantiate(factoryName); if (ob == null) { // could warn, if we had logging system (j.u.l?) return null; } return ((Serializers) ob).findSerializer(config, type, beanDesc); }
public Object[] resolveParameters( Method method, HttpServerRequest request, HttpServerResponse response, Map<String, String> pathParams, Map<String, List<String>> queryParams) throws ParamAnnotationException { Annotation[][] parametersAnnotations = method.getParameterAnnotations(); Class[] parametersTypes = method.getParameterTypes(); Object[] parameters = new Object[parametersTypes.length]; for (int i = 0; i < parametersTypes.length; i++) { Class param = parametersTypes[i]; if (param.isAssignableFrom(request.getClass())) { parameters[i] = request; } else if (param.isAssignableFrom(response.getClass())) { parameters[i] = response; } else { String value = injectParameterValueAnnotation( request, pathParams, queryParams, parametersAnnotations[i]); parameters[i] = paramTypeResolver.resolveValueType(param, value); } } return parameters; }
public AbstractDeserializer(JavaType paramJavaType) { this._baseType = paramJavaType; Class localClass = paramJavaType.getRawClass(); this._acceptString = localClass.isAssignableFrom(String.class); boolean bool1; if ((localClass == Boolean.TYPE) || (localClass.isAssignableFrom(Boolean.class))) { bool1 = true; this._acceptBoolean = bool1; if ((localClass != Integer.TYPE) && (!localClass.isAssignableFrom(Integer.class))) break label110; } label110: for (boolean bool2 = true; ; bool2 = false) { this._acceptInt = bool2; boolean bool3; if (localClass != Double.TYPE) { boolean bool4 = localClass.isAssignableFrom(Double.class); bool3 = false; if (!bool4); } else { bool3 = true; } this._acceptDouble = bool3; return; bool1 = false; break; } }
/** * Get type from primitive object. * * @param val an object of one of the boxed primitive java object classes. * @return <tt>STRING...BOOLEAN</tt> * @throws IllegalArgumentException if type cannot be derived. */ public static int getPrimitiveType(Object val) { if (val instanceof String) { return STRING; } else if (val instanceof Integer) { return INTEGER; } else if (val instanceof Double) { return DOUBLE; } else if (val instanceof Float) { return FLOAT; } else if (val instanceof Integer) { return INTEGER; } else if (val instanceof Long) { return LONG; } else if (val instanceof Boolean) { return BOOLEAN; } else if (val instanceof Short) { return SHORT; } else if (val instanceof Character) { return CHARACTER; } else if (val instanceof Byte) { return BYTE; } else if (BIGINTEGER_OBJECT.isAssignableFrom(val.getClass())) { return BIGINTEGER; } else if (BIGDECIMAL_OBJECT.isAssignableFrom(val.getClass())) { return BIGDECIMAL; } else { throw new IllegalArgumentException("Unsupported type " + val.getClass().getName()); } }
/** * Creates a new ldap attribute values. * * @param t type of values * @throws IllegalArgumentException if t is not a String or byte[] */ public LdapAttributeValues(final Class<T> t) { if (!(t.isAssignableFrom(String.class) || t.isAssignableFrom(byte[].class))) { throw new IllegalArgumentException("Only String and byte[] values are supported"); } type = t; values = createSortBehaviorCollection(type); }
@Override protected <T> T internalValueOfString( final String value, final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale, final Boolean isUnicode, final Class<T> returnType) throws EdmPrimitiveTypeException { if (!Base64.isBase64(value)) { throw new EdmPrimitiveTypeException( "EdmPrimitiveTypeException.LITERAL_ILLEGAL_CONTENT.addContent(value)"); } if (!validateMaxLength(value, maxLength)) { throw new EdmPrimitiveTypeException( "EdmPrimitiveTypeException.LITERAL_FACETS_NOT_MATCHED.addContent(value, facets)"); } final byte[] result = Base64.decodeBase64(value); if (returnType.isAssignableFrom(byte[].class)) { return returnType.cast(result); } else if (returnType.isAssignableFrom(Byte[].class)) { final Byte[] byteArray = new Byte[result.length]; for (int i = 0; i < result.length; i++) { byteArray[i] = result[i]; } return returnType.cast(byteArray); } else { throw new EdmPrimitiveTypeException( "EdmPrimitiveTypeException.VALUE_TYPE_NOT_SUPPORTED.addContent(returnType)"); } }
// TODO document how this is not meant for empty varArgs private static boolean isValidVarArgs(Class<?> varArgType, Object... varArgParams) { boolean result = true; // If there is a single varArgParam, and it's an array already, simply compare their types and // return if (varArgParams.length == 1 && varArgParams[0].getClass().isArray()) { return varArgType.equals(varArgParams[0].getClass()) || varArgType.isAssignableFrom(varArgParams[0].getClass()); } // Get the type of component the varArg array expects Class<?> arrayComponentType = varArgType.getComponentType(); if (arrayComponentType != null) { for (Object o : varArgParams) { if (!arrayComponentType.isAssignableFrom(o.getClass())) { // If the type of array component cannot accept the varArgParam type, end the loop and // this is not a match result = false; break; } } } else { // If the arrayComponetType is null, then this method was improperly called. Meaning something // is broken throw new RuntimeException( "isValidVarArgs(...) called on a non-varArg type, check the invoking code for errors"); } return result; }
/** * In the absence of webapp faces-config.xml and META-INF/services, verify that the overrides * specified in the implementation faces-config.xml take precedence. * * @throws java.lang.Exception */ public void testJSFImplCase() throws Exception { Object factory = null; Class clazz = null; FactoryFinder.releaseFactories(); int len, i = 0; // this testcase only simulates the "faces implementation // specific" part for (i = 0, len = FactoryFinderTestCase2.FACTORIES.length; i < len; i++) { FactoryFinder.setFactory( FactoryFinderTestCase2.FACTORIES[i][0], FactoryFinderTestCase2.FACTORIES[i][1]); } for (i = 0, len = FactoryFinderTestCase2.FACTORIES.length; i < len; i++) { clazz = Class.forName(FactoryFinderTestCase2.FACTORIES[i][0]); factory = FactoryFinder.getFactory(FactoryFinderTestCase2.FACTORIES[i][0]); assertTrue( "Factory for " + clazz.getName() + " not of expected type.", clazz.isAssignableFrom(factory.getClass())); clazz = Class.forName(FactoryFinderTestCase2.FACTORIES[i][1]); assertTrue( "Factory " + FactoryFinderTestCase2.FACTORIES[i][1] + " not of expected type", clazz.isAssignableFrom(factory.getClass())); } }
@SuppressWarnings("unchecked") public <B extends E> boolean add(BoundedHandler<B> handler) { Class<B> newOne = handler.getBoundClass(); if (newOne == getBoundClass()) { // same class as root BoundedHandler<E> bh = (BoundedHandler<E>) handler; boolean targetWasNull = target == null; if (targetWasNull) { target = bh; } return targetWasNull; } else if (getBoundClass().isAssignableFrom(newOne)) { // child of root class for (ClassTree<? extends E> subtree : subclasses.values()) { Class<? extends E> subtreeClass = subtree.getBoundClass(); if (subtreeClass.isAssignableFrom(newOne)) { // subtreeClass is a parent - simply add newOne to subtree ClassTree<? super B> subtree2 = (ClassTree<? super B>) subtree; return subtree2.add(handler); } else if (newOne.isAssignableFrom(subtreeClass)) { // newOne is a parent - remove subtree from this tree, add newOne, add subtreeClass to // newOne as a child ClassTree<? extends B> subtree2 = (ClassTree<? extends B>) subtree; ClassTree<B> value = new ClassTree<B>(handler); value.add(subtree2.target); subclasses.remove(subtreeClass); subclasses.put(newOne, value); return true; } } subclasses.put(newOne, new ClassTree<B>(handler)); return true; } else { return false; } }