Example usage for java.lang Class isInterface

List of usage examples for java.lang Class isInterface

Introduction

In this page you can find the example usage for java.lang Class isInterface.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInterface();

Source Link

Document

Determines if the specified Class object represents an interface type.

Usage

From source file:org.apache.openjpa.meta.MetaDataRepository.java

private Collection<Class<?>> loadPersistentTypesInternal(boolean devpath, ClassLoader envLoader,
        boolean mustExist) {
    Set<String> names = getPersistentTypeNames(devpath, envLoader);
    if (names == null || names.isEmpty()) {
        if (!mustExist)
            return Collections.emptyList();
        else/*ww  w  . j a  v  a2  s. c o m*/
            throw new MetaDataException(_loc.get("eager-no-class-found"));
    }

    // attempt to load classes so that they get processed
    ClassLoader clsLoader = _conf.getClassResolverInstance().getClassLoader(getClass(), envLoader);
    List<Class<?>> classes = new ArrayList<Class<?>>(names.size());
    Class<?> cls;
    for (String className : names) {
        cls = classForName(className, clsLoader);
        if (_factory.isMetaClass(cls)) {
            setMetaModel(cls);
            continue;
        }
        if (cls != null) {
            classes.add(cls);

            // if the class is an interface, load its metadata to kick
            // off the impl generator
            if (cls.isInterface())
                getMetaData(cls, clsLoader, false);
        } else if (cls == null && mustExist) {
            throw new MetaDataException(_loc.get("eager-class-not-found", className));
        }
    }
    return classes;
}

From source file:com.clarkparsia.empire.annotation.RdfGenerator.java

@SuppressWarnings("unchecked")
private static <T> Class<T> determineClass(Class<T> theOrigClass, T theObj, DataSource theSource,
        boolean instanceClass) throws InvalidRdfException, DataSourceException {
    Class aResult = theOrigClass;
    final SupportsRdfId aTmpSupportsRdfId = asSupportsRdfId(theObj);

    //      ExtGraph aGraph = new ExtGraph(DataSourceUtil.describe(theSource, theObj));

    // ======================================== start speedup PATCH ================================================== 
    // get class from uri without quering db

    //      final Collection<Value> aTypes = DataSourceUtil.getValues(theSource, EmpireUtil.asResource(EmpireUtil.asSupportsRdfId(theObj)), RDF.TYPE);

    String rdfId = EmpireUtil.asSupportsRdfId(theObj).getRdfId().toString();
    final Collection<Value> aTypes = Collections
            .singletonList(new URIImpl(StringUtils.substringBeforeLast(rdfId, ":")));
    // ======================================== end speedup PATCH ========================================

    // right now, our best match is the original class (we will refine later)

    //      final Resource aTmpRes = EmpireUtil.asResource(aTmpSupportsRdfId);

    // iterate for all rdf:type triples in the data
    // There may be multiple rdf:type triples, which can then translate onto multiple candidate Java classes
    // some of the Java classes may belong to the same class hierarchy, whereas others can have no common
    // super class (other than java.lang.Object)
    for (Value aValue : aTypes) {
        if (!(aValue instanceof URI)) {
            // there is no URI in the object position of rdf:type
            // ignore that data
            continue;
        }//from  w  w w .jav  a2s .  c o  m

        URI aType = (URI) aValue;

        for (Class aCandidateClass : TYPE_TO_CLASS.get(aType)) {
            if (aCandidateClass.equals(aResult)) {
                // it is mapped to the same Java class, that we have; ignore
                continue;
            }

            // at this point we found an rdf:type triple that resolves to a different Java class than we have
            // we are only going to accept this candidate class if it is a subclass of the current Java class
            // (doing otherwise, may cause class cast exceptions)

            if (aResult.isAssignableFrom(aCandidateClass)) {
                aResult = aCandidateClass;
            }
        }
    }

    try {
        if (instanceClass) {
            if (aResult.isInterface() || Modifier.isAbstract(aResult.getModifiers())
                    || !EmpireGenerated.class.isAssignableFrom(aResult)) {
                aResult = com.clarkparsia.empire.codegen.InstanceGenerator.generateInstanceClass(aResult);
            }
        }
    } catch (Exception e) {
        throw new InvalidRdfException("Cannot generate a class for a bean", e);
    }

    return aResult;
}

From source file:org.blocks4j.reconf.client.constructors.MapConstructor.java

public Object construct(MethodData data) throws Throwable {
    Class<?> returnClass;
    Type keyType = null;/*from w w  w .  j a va 2s.c o m*/
    Type valueType = null;

    if (data.getReturnType() instanceof ParameterizedType) {
        ParameterizedType parameterized = (ParameterizedType) data.getReturnType();
        returnClass = (Class<?>) parameterized.getRawType();

        if (parameterized.getActualTypeArguments().length == 1) {
            Type first = parameterized.getActualTypeArguments()[0];
            if (returnClass.getGenericSuperclass() != null
                    && returnClass.getGenericSuperclass() instanceof ParameterizedType) {
                parameterized = (ParameterizedType) returnClass.getGenericSuperclass();
                if (parameterized.getActualTypeArguments().length != 2) {
                    throw new IllegalArgumentException(
                            msg.format("error.cant.build.type", data.getReturnType(), data.getMethod()));
                }
                if (parameterized.getActualTypeArguments()[0] instanceof TypeVariable) {
                    keyType = first;
                    valueType = parameterized.getActualTypeArguments()[1];

                } else if (parameterized.getActualTypeArguments()[1] instanceof TypeVariable) {
                    valueType = first;
                    keyType = parameterized.getActualTypeArguments()[0];

                } else {
                    throw new IllegalArgumentException(
                            msg.format("error.cant.build.type", data.getReturnType(), data.getMethod()));
                }
            }

        } else {
            keyType = parameterized.getActualTypeArguments()[0];
            valueType = parameterized.getActualTypeArguments()[1];
        }

    } else if (data.getReturnType() instanceof Class) {
        returnClass = (Class<?>) data.getReturnType();

        if (returnClass.getGenericSuperclass() != null
                && returnClass.getGenericSuperclass() instanceof ParameterizedType) {
            ParameterizedType parameterized = (ParameterizedType) returnClass.getGenericSuperclass();
            if (parameterized.getActualTypeArguments().length != 2) {
                throw new IllegalArgumentException(
                        msg.format("error.cant.build.type", data.getReturnType(), data.getMethod()));
            }
            keyType = parameterized.getActualTypeArguments()[0];
            valueType = parameterized.getActualTypeArguments()[1];

        } else {
            keyType = Object.class;
            valueType = Object.class;
        }

    } else {
        throw new IllegalArgumentException(msg.format("error.return", data.getMethod()));
    }

    if (returnClass.isInterface()) {
        returnClass = getDefaultImplementation(data, returnClass);
    }

    Constructor<?> constructor = returnClass.getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY);
    Map<Object, Object> mapInstance = (Map<Object, Object>) constructor
            .newInstance(ArrayUtils.EMPTY_OBJECT_ARRAY);

    if (null == data.getValue() || StringUtils.isEmpty(data.getValue())) {
        return mapInstance;
    }

    if ((!(keyType instanceof Class))
            || (!StringUtils.startsWith(data.getValue(), "[") || !StringUtils.endsWith(data.getValue(), "]"))) {
        throw new IllegalArgumentException(msg.format("error.build", data.getValue(), data.getMethod()));
    }

    StringParser parser = new StringParser(data);
    for (Entry<String, String> each : parser.getTokensAsMap().entrySet()) {
        Object value = ObjectConstructorFactory.get(valueType)
                .construct(new MethodData(data.getMethod(), valueType, each.getValue()));
        mapInstance.put(ObjectConstructorFactory.get(keyType)
                .construct(new MethodData(data.getMethod(), keyType, each.getKey())), value);
    }

    return mapInstance;
}

From source file:org.energy_home.jemma.ah.webui.energyathome.ekitchen.HttpAhBinder.java

public Object invokeMethod(Object targetObject, String methodName, ArrayList paramValues)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    int params = paramValues.size();

    Method[] methods = targetObject.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.getName().compareTo(methodName) == 0) {
            Class[] paramTypes = method.getParameterTypes();
            if (paramTypes.length == params) {

                // HTTP GET params number matches method param number
                Object[] arglist = new Object[params];

                boolean signatureMach = true;
                for (int j = 0; j < params; j++) {
                    Class paramT = paramTypes[j];
                    String typename = paramTypes[j].getName();

                    /*/*  w ww  .  j  a  v  a  2  s .co m*/
                     * currently we support the following param types:
                     * 
                     * Enums, int, short, String
                     */

                    String value = (String) paramValues.get(j).toString();
                    if (typename.compareTo("int") == 0) {
                        arglist[j] = new Integer(value);
                    } else if (typename.compareTo("java.lang.String") == 0) {
                        arglist[j] = value;
                    } else if (typename.compareTo("short") == 0) {
                        arglist[j] = new Short(value);
                    } else if (typename.compareTo("boolean") == 0) {
                        arglist[j] = new Boolean(value);
                    } else if (typename.compareTo("long") == 0) {
                        arglist[j] = new Long(value);
                    } else if (typename.compareTo("[B") == 0) {
                        // convert value (that is an hex string) into a byte
                        // array
                        byte[] v = hexStringToByteArray(value);
                        arglist[j] = v;
                    } else if (typename.equals("java.util.Vector")) {
                        // checks if the passed value represents a JSON
                        // array
                        if ((value.length() >= 2) && (value.charAt(0) == '[')) {
                            JSONArray outer;
                            try {
                                outer = new JSONArray(value);
                            } catch (JSONException e) {
                                signatureMach = false;
                                break;
                            }

                            // convert the json array into a Vector
                            Vector v = new Vector();

                            for (int k = 0; k < outer.length(); k++) {
                                try {
                                    v.add(outer.get(k));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (v instanceof Vector) {
                                arglist[j] = v;
                            }
                        }
                    } else if (paramT.isInterface()) {
                        Object o = getObjectByPid(value);
                        if (o != null) {
                            arglist[j] = o;
                        } else {
                            signatureMach = false;
                            break;
                        }
                    } else {
                        log.warn("unsupported type '" + typename + "'in target signature");
                        signatureMach = false;
                        break;

                    }
                }

                if (signatureMach) {
                    Object result = null;
                    result = method.invoke(targetObject, arglist);
                    return this.resultToJSON(result);
                } else {
                    log.error("signature not found for method " + methodName);
                }
            }
        }
    }

    throw new RuntimeException("Could not find the method " + methodName + " parameters or name doesn't match");
}

From source file:Main.java

/**
 * convert value to given type./*  w w  w .j  a  v  a 2 s  . c o  m*/
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) {

    Assert.notNull(clazz, "clazz must not be null");
    Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null");

    ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig);
    SoftReference<ModelBean> modelReference = modelCache.get(key);
    if (modelReference != null && modelReference.get() != null) {
        return modelReference.get();
    }//from   w  ww .j  a  v a2 s  .  c om

    Model modelAnnotation = clazz.getAnnotation(Model.class);

    final ModelBean model = new ModelBean();

    if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) {
        model.setName(modelAnnotation.value());
    } else {
        model.setName(clazz.getName());
    }

    if (modelAnnotation != null) {
        model.setAutodetectTypes(modelAnnotation.autodetectTypes());
    }

    if (modelAnnotation != null) {
        model.setExtend(modelAnnotation.extend());
        model.setIdProperty(modelAnnotation.idProperty());
        model.setVersionProperty(trimToNull(modelAnnotation.versionProperty()));
        model.setPaging(modelAnnotation.paging());
        model.setDisablePagingParameters(modelAnnotation.disablePagingParameters());
        model.setCreateMethod(trimToNull(modelAnnotation.createMethod()));
        model.setReadMethod(trimToNull(modelAnnotation.readMethod()));
        model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod()));
        model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod()));
        model.setMessageProperty(trimToNull(modelAnnotation.messageProperty()));
        model.setWriter(trimToNull(modelAnnotation.writer()));
        model.setReader(trimToNull(modelAnnotation.reader()));
        model.setSuccessProperty(trimToNull(modelAnnotation.successProperty()));
        model.setTotalProperty(trimToNull(modelAnnotation.totalProperty()));
        model.setRootProperty(trimToNull(modelAnnotation.rootProperty()));
        model.setWriteAllFields(modelAnnotation.writeAllFields());
        model.setIdentifier(trimToNull(modelAnnotation.identifier()));
        String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty());
        if (StringUtils.hasText(clientIdProperty)) {
            model.setClientIdProperty(clientIdProperty);
            model.setClientIdPropertyAddToWriter(true);
        } else {
            model.setClientIdProperty(null);
            model.setClientIdPropertyAddToWriter(false);
        }
    }

    final Set<String> hasReadMethod = new HashSet<String>();

    BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) {
            hasReadMethod.add(pd.getName());
        }
    }

    if (clazz.isInterface()) {
        final List<Method> methods = new ArrayList<Method>();

        ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                methods.add(method);
            }
        });

        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        for (Method method : methods) {
            createModelBean(model, method, outputConfig);
        }
    } else {

        final Set<String> fields = new HashSet<String>();

        Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class,
                ModelField.class);
        for (ModelField modelField : modelFieldsOnType) {
            if (StringUtils.hasText(modelField.value())) {
                ModelFieldBean modelFieldBean;

                if (StringUtils.hasText(modelField.customType())) {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType());
                } else {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type());
                }

                updateModelFieldBean(modelFieldBean, modelField);
                model.addField(modelFieldBean);
            }
        }

        Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelAssociations.class, ModelAssociation.class);
        for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) {
            AbstractAssociation modelAssociation = AbstractAssociation
                    .createAssociation(modelAssociationAnnotation);
            if (modelAssociation != null) {
                model.addAssociation(modelAssociation);
            }
        }

        Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelValidations.class, ModelValidation.class);
        for (ModelValidation modelValidationAnnotation : modelValidationsOnType) {
            AbstractValidation modelValidation = AbstractValidation.createValidation(
                    modelValidationAnnotation.propertyName(), modelValidationAnnotation,
                    outputConfig.getIncludeValidation());
            if (modelValidation != null) {
                model.addValidation(modelValidation);
            }
        }

        ReflectionUtils.doWithFields(clazz, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null
                        || field.getAnnotation(ModelAssociation.class) != null
                        || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName()))
                                && field.getAnnotation(JsonIgnore.class) == null)) {

                    // ignore superclass declarations of fields already
                    // found in a subclass
                    fields.add(field.getName());
                    createModelBean(model, field, outputConfig);

                }
            }

        });
    }

    modelCache.put(key, new SoftReference<ModelBean>(model));
    return model;
}

From source file:org.ajax4jsf.builder.config.ComponentBaseBean.java

/**
 * @param superClass/*w ww.  j  a va 2  s .co  m*/
 */
private void checkPropertiesForClass(Class<?> superClass) {
    getLog().debug("Check properties for class " + superClass.getName());
    // get all property descriptors
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(superClass);
    // for all properties, add it to component. If property have not abstract getter/setter ,
    // add it with exist = true . If property in list of hidden names, set hidden = true.
    PropertyBean property;
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor descriptor = properties[i];
        if (!containProperty(descriptor.getName())) {
            if (isIgnorableProperty(superClass, descriptor.getName())) {
                continue;
            }
            Class<?> type = descriptor.getPropertyType();
            getLog().debug("Register property  " + descriptor.getName() + " with type name "
                    + type.getCanonicalName());
            property = new PropertyBean();
            property.setName(descriptor.getName());
            property.setDescription(descriptor.getShortDescription());
            property.setDisplayname(descriptor.getDisplayName());
            property.setClassname(descriptor.getPropertyType().getCanonicalName());
            property.setExist(true);
            addProperty(property);
        } else {
            // Load and check property.
            getLog().debug("Check  property  " + descriptor.getName());
            property = (PropertyBean) this.properties.get(descriptor.getName());
            if (property.getClassname() == null) {
                property.setClassname(descriptor.getPropertyType().getCanonicalName());
            } else {
                if (!property.getClassname().equals(descriptor.getPropertyType().getCanonicalName())) {
                    String message = "Class " + property.getClassname() + " for property " + property.getName()
                            + " not equals with real bean property type: "
                            + descriptor.getPropertyType().getCanonicalName();
                    getLog().error(message);
                    //throw new IllegalArgumentException(message);
                }
            }
            if (property.getDescription() == null) {
                property.setDescription(descriptor.getShortDescription());
            }
            if (property.getDisplayname() == null) {
                property.setDisplayname(descriptor.getDisplayName());
            }
            property.setExist(true);
        }
        Method getter = descriptor.getReadMethod();
        Method setter = descriptor.getWriteMethod();
        // Abstract methods
        if (null != setter && null != getter) {
            if ((Modifier.isAbstract(getter.getModifiers()) && Modifier.isAbstract(setter.getModifiers()))
                    || superClass.isInterface()) {
                getLog().debug("Detect as abstract property  " + descriptor.getName());
                property.setExist(false);
            }
        }

        if (null == setter || (!Modifier.isPublic(setter.getModifiers()))) {
            getLog().debug("Detect as hidden property  " + descriptor.getName());
            property.setHidden(true);
        }
        if (isAttachedProperty(property)) {
            property.setAttachedstate(true);
        }
        if (property.isInstanceof("javax.faces.el.MethodBinding")
                || property.isInstanceof("javax.faces.el.ValueBinding")) {
            property.setElonly(true);
        }

    }
}

From source file:org.apache.jackrabbit.ocm.manager.objectconverter.impl.ObjectConverterImpl.java

/**
 * @see org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter#getObject(javax.jcr.Session,
 *      java.lang.Class, java.lang.String)
 *//*from  ww  w .  ja  va  2s . com*/
public Object getObject(Session session, Class clazz, String path) {
    try {
        if (!session.itemExists(path)) {
            return null;
        }

        if (requestObjectCache.isCached(path)) {
            return requestObjectCache.getObject(path);
        }

        ClassDescriptor classDescriptor = getClassDescriptor(clazz);

        checkNodeType(session, classDescriptor);

        Node node = (Node) session.getItem(path);
        if (!classDescriptor.isInterface()) {
            node = getActualNode(session, node);
            checkCompatiblePrimaryNodeTypes(session, node, classDescriptor, true);
        }

        ClassDescriptor alternativeDescriptor = null;
        if (classDescriptor.usesNodeTypePerHierarchyStrategy()) {
            if (node.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) {
                String className = node.getProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)
                        .getValue().getString();
                alternativeDescriptor = getClassDescriptor(ReflectionUtils.forName(className));
            }
        } else {
            if (classDescriptor.usesNodeTypePerConcreteClassStrategy()) {
                String nodeType = node.getPrimaryNodeType().getName();
                if (!nodeType.equals(classDescriptor.getJcrType())) {
                    alternativeDescriptor = classDescriptor.getDescendantClassDescriptor(nodeType);

                    // in case we an alternative could not be found by walking
                    // the class descriptor hierarchy, check whether we would
                    // have a descriptor for the node type directly (which
                    // may the case if the class descriptor hierarchy is
                    // incomplete due to missing configuration. See JCR-1145
                    // for details.
                    if (alternativeDescriptor == null) {
                        alternativeDescriptor = mapper.getClassDescriptorByNodeType(nodeType);
                    }
                }
            }
        }

        // if we have an alternative class descriptor, check whether its
        // extends (or is the same) as the requested class.
        if (alternativeDescriptor != null) {
            Class alternativeClazz = ReflectionUtils.forName(alternativeDescriptor.getClassName());
            if (clazz.isAssignableFrom(alternativeClazz)) {
                clazz = alternativeClazz;
                classDescriptor = alternativeDescriptor;
            }
        }

        // ensure class is concrete (neither interface nor abstract)
        if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
            throw new JcrMappingException("Cannot instantiate non-concrete class " + clazz.getName()
                    + " for node " + path + " of type " + node.getPrimaryNodeType().getName());
        }

        Object object = ReflectionUtils.newInstance(classDescriptor.getClassName());

        if (!requestObjectCache.isCached(path)) {
            requestObjectCache.cache(path, object);
        }

        simpleFieldsHelp.retrieveSimpleFields(session, classDescriptor, node, object);
        retrieveBeanFields(session, classDescriptor, node, path, object, false);
        retrieveCollectionFields(session, classDescriptor, node, object, false);

        return object;
    } catch (PathNotFoundException pnfe) {
        // HINT should never get here
        throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe);
    } catch (RepositoryException re) {
        throw new org.apache.jackrabbit.ocm.exception.RepositoryException(
                "Impossible to get the object at " + path, re);
    }
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

public <T> T generateRandom(Type type, Map<String, Type> itestGenericMap, ITestContext iTestContext) {
    ITestParamState iTestState = iTestContext.getCurrentParam();
    Class<?> clazz = ITestTypeUtil.getRawClass(type);

    Class<?> requestedClass = getClassFromParam(iTestState);
    if (null != iTestState && null != iTestState.getAttribute(ITestConstants.ATTRIBUTE_DEFINITION)) {
        ITestParamState iTestStateLoaded = iTestConfig.getITestParamLoader()
                .loadITestParam(null == requestedClass ? clazz : requestedClass,
                        iTestState.getAttribute(ITestConstants.ATTRIBUTE_DEFINITION))
                .getElement(ITestConstants.THIS);
        iTestState = iTestConfig.getITestParamsMerger().merge(
                new ITestParamAssignmentImpl("", iTestStateLoaded),
                new ITestParamAssignmentImpl("", iTestState));
        iTestContext.replaceCurrentState(iTestState);
    }/*from   w  w  w .j  av a2s.  c om*/

    Object res;
    if (ITestParamState.class == clazz) {
        res = processITestState(iTestContext);
    } else if (null != iTestState && null == iTestState.getSizeParam() && null == iTestState.getValue()) {
        res = null;
    } else if (null != iTestState && null != iTestState.getAttribute(ITestConstants.REFERENCE_ATTRIBUTE)) {
        res = iTestContext.findGeneratedObject(iTestState.getAttribute(ITestConstants.REFERENCE_ATTRIBUTE));
    } else if (PROXY_CLASS == requestedClass) {
        res = newDynamicProxy(type, itestGenericMap, iTestContext);
    } else if (Collection.class.isAssignableFrom(clazz)) {
        res = fillCollection(null, type, itestGenericMap, iTestContext);
    } else if (Map.class.isAssignableFrom(clazz)) {
        res = fillMap(null, type, itestGenericMap, iTestContext);
    } else if (null != requestedClass) {
        res = generateRandom(requestedClass, itestGenericMap, iTestContext);
    } else if (type instanceof GenericArrayType) {
        GenericArrayType arrayType = (GenericArrayType) type;
        Class<?> componentClass;
        int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN;
        if (null != iTestState && iTestState.getSizeParam() != null) {
            size = iTestState.getSizeParam();
        }
        Map<String, Type> map = new HashMap<String, Type>(itestGenericMap);
        if (arrayType.getGenericComponentType() instanceof ParameterizedType) {
            componentClass = (Class<?>) ((ParameterizedType) arrayType.getGenericComponentType()).getRawType();

        } else {
            componentClass = (Class<?>) arrayType.getGenericComponentType();
        }
        Object array = Array.newInstance(componentClass, size);
        for (int i = 0; i < size; i++) {
            ITestParamState elementITestState = iTestState == null ? null
                    : iTestState.getElement(String.valueOf(i));
            Array.set(array, i, generateRandom(arrayType.getGenericComponentType(), map, iTestContext));
        }
        res = array;
    } else if (null != iTestState && null == iTestState.getNames()) {
        res = iTestConfig.getITestValueConverter().convert(clazz, iTestState.getValue());
    } else if (clazz.isInterface()) {
        res = newDynamicProxy(type, itestGenericMap, iTestContext);
    } else if (type instanceof Class) {
        res = generateRandom(clazz, itestGenericMap, iTestContext);
    } else if (Enum.class == clazz) {
        Type enumType = ITestTypeUtil.getTypeProxy(((ParameterizedType) type).getActualTypeArguments()[0],
                itestGenericMap);
        res = generateRandom(enumType, itestGenericMap, iTestContext);
    } else if (Class.class == clazz) {
        // probably proxy will be required here
        res = ((ParameterizedType) type).getActualTypeArguments()[0];
    } else {

        Map<String, Type> map = ITestTypeUtil.getTypeMap(type, itestGenericMap);
        res = newInstance(clazz, iTestContext, ITestTypeUtil.getTypeActualArguments(type));
        fillFields(clazz, res, iTestState, map, iTestContext);
    }
    return (T) res;
}

From source file:com.clarkparsia.empire.annotation.RdfGenerator.java

private static Class refineClass(final Object theAccessor, final Class theClass, final DataSource theSource,
        final Resource theId) {
    Class aClass = theClass;

    if (Collection.class.isAssignableFrom(aClass)) {
        // if the field we're assigning from is a collection, try and figure out the type of the thing
        // we're creating from the collection

        Type[] aTypes = null;/*from   www . ja va 2s .  com*/

        if (theAccessor instanceof Field
                && ((Field) theAccessor).getGenericType() instanceof ParameterizedType) {
            aTypes = ((ParameterizedType) ((Field) theAccessor).getGenericType()).getActualTypeArguments();
        } else if (theAccessor instanceof Method) {
            aTypes = ((Method) theAccessor).getGenericParameterTypes();
        }

        if (aTypes != null && aTypes.length >= 1) {
            // first type argument to a collection is usually the one we care most about
            if (aTypes[0] instanceof ParameterizedType
                    && ((ParameterizedType) aTypes[0]).getActualTypeArguments().length > 0) {
                Type aType = ((ParameterizedType) aTypes[0]).getActualTypeArguments()[0];

                if (aType instanceof Class) {
                    aClass = (Class) aType;
                } else if (aType instanceof WildcardTypeImpl) {
                    WildcardTypeImpl aWildcard = (WildcardTypeImpl) aType;
                    // trying to suss out super v extends w/o resorting to string munging.
                    if (aWildcard.getLowerBounds().length == 0 && aWildcard.getUpperBounds().length > 0) {
                        // no lower bounds afaik indicates ? extends Foo
                        aClass = ((Class) aWildcard.getUpperBounds()[0]);
                    } else if (aWildcard.getLowerBounds().length > 0) {
                        // lower & upper bounds I believe indicates something of the form Foo super Bar
                        aClass = ((Class) aWildcard.getLowerBounds()[0]);
                    } else {
                        // shoot, we'll try the string hack that Adrian posted on the mailing list.
                        try {
                            aClass = Class.forName(aType.toString().split(" ")[2].substring(0,
                                    aTypes[0].toString().split(" ")[2].length() - 1));
                        } catch (Exception e) {
                            // everything has failed, let aClass be the default (theClass) and hope for the best
                        }
                    }
                } else {
                    // punt? wtf else could it be?
                    try {
                        aClass = Class.forName(aType.toString());
                    } catch (ClassNotFoundException e) {
                        // oh well, we did the best we can
                    }
                }
            } else if (aTypes[0] instanceof Class) {
                aClass = (Class) aTypes[0];
            }
        } else {
            // could not figure out the type from the generics assertions on the Collection, they are either
            // not present, or my algorithm is not bullet proof.  So lets try checking on the annotations
            // for a type hint.

            Class aTarget = BeanReflectUtil.getTargetEntity(theAccessor);
            if (aTarget != null) {
                aClass = aTarget;
            }
        }
    }

    if (!BeanReflectUtil.hasAnnotation(aClass, RdfsClass.class) || aClass.isInterface()) {
        // k, so either the parameter of the collection or the declared type of the field does
        // not map to an instance/bean type.  this is most likely an error, but lets try and find
        // the rdf:type of the field, and see if we can map that to a class in the path and we'll
        // create an instance of that.  that will work, and pushes the likely failure back off to
        // the assignment of the created instance

        Iterable<Resource> aTypes = DataSourceUtil.getTypes(theSource, theId);

        // k, so now we know the type, if we can match the type to a class then we're in business
        for (Resource aType : aTypes) {
            if (aType instanceof URI) {
                for (Class aTypeClass : TYPE_TO_CLASS.get((URI) aType)) {
                    if ((BeanReflectUtil.hasAnnotation(aTypeClass, RdfsClass.class))
                            && (aClass.isAssignableFrom(aTypeClass))) {
                        // lets try this one
                        aClass = aTypeClass;
                        break;
                    }
                }
            }
        }
    }

    if (aClass.isInterface()) {
        if (BeanReflectUtil.hasAnnotation(aClass, RdfsClass.class)) {
            URI aType = FACTORY.createURI(((RdfsClass) aClass.getAnnotation(RdfsClass.class)).value());
            for (Class aTypeClass : TYPE_TO_CLASS.get(aType)) {
                if ((BeanReflectUtil.hasAnnotation(aTypeClass, RdfsClass.class))
                        && (aClass.isAssignableFrom(aTypeClass))) {
                    // lets try this one
                    aClass = aTypeClass;
                    return aClass;
                }
            }
        }
    }

    return aClass;
}