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.datacache.QueryKey.java

/**
 * Extract the relevant identifying information from
 * <code>q</code>. This includes information such as candidate
 * class, query filter, etc./*  ww  w . j av  a  2  s  .co m*/
 */
private static QueryKey createKey(QueryContext q, boolean packed, Class<?> candidateClass, boolean subclasses,
        long startIdx, long endIdx, Object parsed) {
    if (candidateClass == null)
        return null;

    // can only cache datastore queries
    if (q.getCandidateCollection() != null)
        return null;

    // no support already-packed results
    if (q.getResultType() != null && packed)
        return null;

    // can't cache non-serializable non-managed complex types
    Class<?>[] types = q.getProjectionTypes();
    for (int i = 0; i < types.length; i++) {
        switch (JavaTypes.getTypeCode(types[i])) {
        case JavaTypes.ARRAY:
            return null;
        case JavaTypes.COLLECTION:
        case JavaTypes.MAP:
        case JavaTypes.OBJECT:
            if (!ImplHelper.isManagedType(q.getStoreContext().getConfiguration(), types[i]))
                return null;
            break;
        }
    }

    // we can't cache the query if we don't know which classes are in the
    // access path
    ClassMetaData[] metas = q.getAccessPathMetaDatas();
    if (metas.length == 0)
        return null;

    Set<String> accessPathClassNames = new HashSet<String>((int) (metas.length * 1.33 + 1));
    ClassMetaData meta;
    for (int i = 0; i < metas.length; i++) {
        // since the class change framework deals with least-derived types,
        // record the least-derived access path types
        meta = metas[i];
        accessPathClassNames.add(meta.getDescribedType().getName());
        while (meta.getPCSuperclass() != null) {
            meta = meta.getPCSuperclassMetaData();
        }

        accessPathClassNames.add(meta.getDescribedType().getName());
    }

    // if any of the types are currently dirty, we can't cache this query
    StoreContext ctx = q.getStoreContext();
    if (intersects(accessPathClassNames, ctx.getPersistedTypes())
            || intersects(accessPathClassNames, ctx.getUpdatedTypes())
            || intersects(accessPathClassNames, ctx.getDeletedTypes()))
        return null;

    // calculate the timeout for the key
    MetaDataRepository repos = ctx.getConfiguration().getMetaDataRepositoryInstance();

    // won't find metadata for interfaces.
    if (candidateClass.isInterface())
        return null;
    meta = repos.getMetaData(candidateClass, ctx.getClassLoader(), true);
    int timeout = meta.getDataCacheTimeout();
    if (subclasses) {
        metas = meta.getPCSubclassMetaDatas();
        int subTimeout;
        for (int i = 0; i < metas.length; i++) {
            if (metas[i].getDataCache() == null)
                return null;

            accessPathClassNames.add(metas[i].getDescribedType().getName());
            subTimeout = metas[i].getDataCacheTimeout();
            if (subTimeout != -1 && subTimeout < timeout)
                timeout = subTimeout;
        }
    }

    // tests all passed; cacheable
    QueryKey key = new QueryKey();
    key._candidateClassName = candidateClass.getName();
    key._subclasses = subclasses;
    key._accessPathClassNames = accessPathClassNames;
    key._timeout = timeout;
    key._query = q.getQueryString();
    if (key._query == null && parsed != null) {
        // this is a criteria query. Store the Stringified query value rather than the full cq.
        key._query = parsed.toString();
    }
    key._ignoreChanges = q.getIgnoreChanges();
    key._rangeStart = startIdx;
    key._rangeEnd = endIdx;
    return key;
}

From source file:com.app.server.EJBDeployer.java

public void deployEjbJar(URL url, StandardFileSystemManager manager, ClassLoader cL) {
    try {//w  w w  .  j  av  a2 s.  c o  m
        Vector<EJBContext> ejbContexts = null;
        EJBContext ejbContext;
        log.info(url.toURI());
        ConcurrentHashMap<String, RARArchiveData> rardata = (ConcurrentHashMap<String, RARArchiveData>) mbeanServer
                .getAttribute(rarDeployerName, "RARArchiveDataAllAdapters");
        Collection<RARArchiveData> rarcls = rardata.values();
        Iterator<RARArchiveData> rarcl = rarcls.iterator();
        RARArchiveData rararcdata;

        FileObject filetoScan = manager.resolveFile("jar:" + url.toString() + "!/");
        HashSet<Class<?>>[] classes = new HashSet[] { new HashSet(), new HashSet(), new HashSet() };

        VFSClassLoader jarCL;

        if (cL != null) {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager, cL);
        } else {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager,
                    Thread.currentThread().getContextClassLoader());
        }
        Class[] annot = new Class[] { Stateless.class, Stateful.class, MessageDriven.class };
        scanJar(filetoScan, classes, annot, jarCL);
        Set<Class<?>> clsStateless = classes[0];
        Set<Class<?>> clsStateful = classes[1];
        Set<Class<?>> clsMessageDriven = classes[2];
        //System.gc();
        staticObjs = null;
        EJBContainer container = EJBContainer.getInstance(classes);
        container.inject();
        if (clsStateless.size() > 0) {
            staticObjs = new Vector<Object>();
            ejbContexts = new Vector<EJBContext>();
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            for (Class<?> ejbInterface : clsStateless) {
                BeanPool.getInstance().create(ejbInterface);
                obj = BeanPool.getInstance().get(ejbInterface);
                System.out.println(obj);
                ProxyFactory factory = new ProxyFactory();
                proxyobj = factory.createWithBean(obj);
                staticObjs.add(proxyobj);
                Object unicastobj = UnicastRemoteObject.exportObject((Remote) proxyobj, 0);
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + obj);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, (Remote) unicastobj);
                    ejbContext.put(remoteBinding, obj.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsStateful.size() > 0) {
            if (staticObjs == null) {
                staticObjs = new Vector<Object>();
            }
            if (ejbContexts == null) {
                ejbContexts = new Vector<EJBContext>();
            }
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            StatefulBeanObject statefulBeanObject = null;
            for (Class<?> ejbInterface : clsStateful) {
                BeanPool.getInstance().create(ejbInterface);
                obj1 = ejbInterface.newInstance();
                if (statefulBeanObject == null) {
                    statefulBeanObject = new StatefulBeanObject(obj1, url.toString());
                } else {
                    statefulBeanObject.addStatefulSessionBeanObject(obj1);
                }
                //System.out.println(obj1);
                staticObjs.add(statefulBeanObject);
                /*Object unicastobj1 = UnicastRemoteObject.exportObject(
                      (Remote) obj1,
                      0);*/
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + statefulBeanObject);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, statefulBeanObject);
                    ejbContext.put(remoteBinding, statefulBeanObject.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj1);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsMessageDriven.size() > 0) {

            MDBContext mdbContext = null;
            ConcurrentHashMap<String, MDBContext> mdbContexts;
            if (jarMDBMap.get(url.toString()) != null) {
                mdbContexts = jarMDBMap.get(url.toString());
            } else {
                mdbContexts = new ConcurrentHashMap<String, MDBContext>();
            }
            jarMDBMap.put(url.toString(), mdbContexts);
            MDBContext mdbContextOld;
            for (Class<?> mdbBean : clsMessageDriven) {
                String classwithpackage = mdbBean.getName();
                //System.out.println("class package" + classwithpackage);
                classwithpackage = classwithpackage.replace("/", ".");
                //System.out.println("classList:"
                //   + classwithpackage.replace("/", "."));
                final Class mdbBeanCls = mdbBean;
                try {
                    if (!classwithpackage.contains("$")) {
                        // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        // System.out.println();
                        if (!mdbBean.isInterface()) {
                            Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                            if (classServicesAnnot != null) {
                                Adapter adapter = null;
                                ActivationConfigProperty[] activationConfigProp = null;
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof Adapter) {
                                        adapter = (Adapter) classServicesAnnot[annotcount];
                                    } else if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                        MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                        activationConfigProp = messageDrivenAnnot.activationConfig();
                                        mdbContext = new MDBContext();
                                        mdbContext.setMdbName(messageDrivenAnnot.name());
                                    }
                                }
                                if (adapter != null) {
                                    /*if(rarcl.hasNext()){
                                       rararcdata=rardata.get(rarDeployerName);
                                          rararcdata=rarcl.next();
                                          //classLoader = new VFSClassLoader(rararcdata.getVfsClassLoader().getFileObjects(),rararcdata.getFsManager(),classLoader);
                                          FileObject[] fileObjectArray=rararcdata.getVfsClassLoader().getFileObjects();
                                          //urlset.addAll(ClasspathHelper.forClassLoader(rararcdata.getVfsClassLoader()));
                                          for(FileObject fileObject:fileObjectArray){
                                             fileObjects.add(fileObject.getURL());
                                             //urlset.add(fileObject.getURL());
                                             //System.out.println(Vfs.fromURL(fileObject.getURL()).getFiles().iterator().next().getRelativePath());
                                          }
                                          classLoader = new URLClassLoader(fileObjects.toArray(new URL[fileObjects.size()]),Thread.currentThread().getContextClassLoader());
                                    }*/
                                    RARArchiveData rarArchiveData = (RARArchiveData) mbeanServer.invoke(
                                            rarDeployerName, "getRARArchiveData",
                                            new Object[] { adapter.adapterName() },
                                            new String[] { String.class.getName() });
                                    if (rarArchiveData == null)
                                        throw new Exception("RAR Adapter " + adapter.adapterName()
                                                + " Not found in deploy folder");
                                    Class resourceAdapterClass = rarArchiveData.getResourceAdapterClass();
                                    final ResourceAdapter resourceAdapter = (ResourceAdapter) resourceAdapterClass
                                            .newInstance();
                                    Class activationSpecClass = rarArchiveData.getActivationspecclass();
                                    final ActivationSpec activationSpec = (ActivationSpec) activationSpecClass
                                            .newInstance();
                                    Vector<ConfigProperty> configProperties = rarArchiveData.getConfigPropery();
                                    Integer configPropertyInteger;
                                    Long configPropertyLong;
                                    Boolean configPropertyBoolean;
                                    Method method;
                                    if (configProperties != null) {
                                        for (ConfigProperty configProperty : configProperties) {
                                            String property = configProperty.getConfigpropertyname();
                                            property = (property.charAt(0) + "").toUpperCase()
                                                    + property.substring(1);
                                            Class propertytype = Class
                                                    .forName(configProperty.getConfigpropertytype());
                                            try {

                                                method = activationSpecClass.getMethod("set" + property,
                                                        propertytype);
                                                if (propertytype == String.class) {
                                                    method.invoke(activationSpec,
                                                            configProperty.getConfigpropertyvalue());
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } else if (propertytype == Integer.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyInteger = new Integer(
                                                                configProperty.getConfigpropertyvalue());
                                                        try {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger);
                                                        } catch (Exception ex) {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                        }
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Long.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyLong = new Long(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyLong);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Boolean.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyBoolean = new Boolean(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyBoolean);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                }
                                            } catch (Exception ex) {
                                                try {
                                                    if (propertytype == Integer.class) {
                                                        method = activationSpecClass.getMethod("set" + property,
                                                                int.class);
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, int.class);
                                                            configPropertyInteger = new Integer(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);                                       
                                                        }
                                                    } else if (propertytype == Long.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, long.class);
                                                            configPropertyLong = new Long(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyLong.longValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    } else if (propertytype == Boolean.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, boolean.class);
                                                            configPropertyBoolean = new Boolean(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyBoolean.booleanValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    }
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } catch (Exception ex1) {
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                }
                                                //log.error("Could not set Configuration for rar activation spec", ex);
                                            }
                                        }
                                    }
                                    for (ActivationConfigProperty activationConfig : activationConfigProp) {
                                        String property = activationConfig.propertyName();
                                        property = (property.charAt(0) + "").toUpperCase()
                                                + property.substring(1);
                                        try {
                                            method = activationSpecClass.getMethod("set" + property,
                                                    String.class);
                                            method.invoke(activationSpec, activationConfig.propertyValue());
                                        } catch (Exception ex) {
                                            try {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            } catch (Exception ex1) {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        Boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            }
                                        }

                                    }
                                    final Class listenerClass = rarArchiveData.getMessagelistenertype();
                                    ClassLoader cCL = Thread.currentThread().getContextClassLoader();
                                    Thread.currentThread()
                                            .setContextClassLoader(resourceAdapter.getClass().getClassLoader());
                                    resourceAdapter
                                            .start(new com.app.server.connector.impl.BootstrapContextImpl());
                                    MessageEndPointFactoryImpl messageEndPointFactoryImpl = new MessageEndPointFactoryImpl(
                                            listenerClass, mdbBeanCls.newInstance(), jarCL);
                                    resourceAdapter.endpointActivation(messageEndPointFactoryImpl,
                                            activationSpec);
                                    Thread.currentThread().setContextClassLoader(cCL);
                                    if (mdbContext != null) {
                                        mdbContext.setResourceAdapter(resourceAdapter);
                                        mdbContext.setMessageEndPointFactory(messageEndPointFactoryImpl);
                                        mdbContext.setActivationSpec(activationSpec);
                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                    }
                                    /*new Thread(){
                                       public void run(){
                                          try {
                                             resourceAdapter.endpointActivation(new com.app.server.connector.impl.MessageEndPointFactoryImpl(listenerClass, mdbBeanCls.newInstance(),raCl), activationSpec);
                                          } catch (
                                                Exception e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                                          }
                                       }
                                    }.start();*/

                                } else {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("Error : ", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
            }
        }
        if (staticObjs != null) {
            staticObjsEjbMap.put(url.toString(), staticObjs);
        }
        this.jarsDeployed.add(url.toURI().toString());
        log.info(url.toString() + " Deployed");
    } catch (Exception ex) {
        log.error("Error in deploying the jar file: " + url, ex);
        //ex.printStackTrace();
    } finally {
        /*if(classLoader!=null){
           try {
              classLoader.close();
           } catch (Exception e) {
              log.error("error in closing the classloader", e);
              // TODO Auto-generated catch block
              //e.printStackTrace();
           }
           ClassLoaderUtil.closeClassLoader(classLoader);
        }*/
    }

}

From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirDao.java

private void validateChildReferences(IBase theElement, String thePath) {
    if (theElement == null) {
        return;//ww w  .j  a va 2  s.  co  m
    }
    BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition(theElement.getClass());
    if (!(def instanceof BaseRuntimeElementCompositeDefinition)) {
        return;
    }

    BaseRuntimeElementCompositeDefinition<?> cdef = (BaseRuntimeElementCompositeDefinition<?>) def;
    for (BaseRuntimeChildDefinition nextChildDef : cdef.getChildren()) {

        List<IBase> values = nextChildDef.getAccessor().getValues(theElement);
        if (values == null || values.isEmpty()) {
            continue;
        }

        String newPath = thePath + "." + nextChildDef.getElementName();

        for (IBase nextChild : values) {
            validateChildReferences(nextChild, newPath);
        }

        if (nextChildDef instanceof RuntimeChildResourceDefinition) {
            RuntimeChildResourceDefinition nextChildDefRes = (RuntimeChildResourceDefinition) nextChildDef;
            Set<String> validTypes = new HashSet<String>();
            boolean allowAny = false;
            for (Class<? extends IBaseResource> nextValidType : nextChildDefRes.getResourceTypes()) {
                if (nextValidType.isInterface()) {
                    allowAny = true;
                    break;
                }
                validTypes.add(getContext().getResourceDefinition(nextValidType).getName());
            }

            if (allowAny) {
                continue;
            }

            for (IBase nextChild : values) {
                IBaseReference nextRef = (IBaseReference) nextChild;
                if (!isBlank(nextRef.getReferenceElement().getResourceType())) {
                    if (!nextRef.getReferenceElement().getValue().contains("?")) {
                        if (!validTypes.contains(nextRef.getReferenceElement().getResourceType())) {
                            throw new UnprocessableEntityException("Invalid reference found at path '" + newPath
                                    + "'. Resource type '" + nextRef.getReferenceElement().getResourceType()
                                    + "' is not valid for this path");
                        }
                    }
                }
            }

        }
    }
}

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

public Object construct(MethodData data) throws Throwable {
    Class<?> returnClass;
    Type innerClass = null;//ww  w  .ja v  a  2 s  .  com

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

        if (parameterized.getActualTypeArguments()[0] instanceof ParameterizedType) {
            innerClass = parameterized.getActualTypeArguments()[0];

        } else if (parameterized.getActualTypeArguments()[0] instanceof Class<?>) {
            innerClass = parameterized.getActualTypeArguments()[0];
        }
    } 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 != 1) {
                throw new IllegalArgumentException(
                        msg.format("error.cant.build.type", data.getReturnType(), data.getMethod()));
            }
            if (parameterized.getActualTypeArguments()[0] instanceof TypeVariable) {
                throw new IllegalArgumentException(
                        msg.format("error.cant.build.type", data.getReturnType(), data.getMethod()));
            } else {
                innerClass = parameterized.getActualTypeArguments()[0];
            }

        } else {
            innerClass = 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);
    Collection<Object> collectionInstance = (Collection<Object>) constructor
            .newInstance(ArrayUtils.EMPTY_OBJECT_ARRAY);

    if (null == data.getValue()) {
        return collectionInstance;
    }

    for (String s : new StringParser(data).getTokens()) {
        Object o = ObjectConstructorFactory.get(innerClass)
                .construct(new MethodData(data.getMethod(), innerClass, s));
        if (o != null) {
            collectionInstance.add(o);
        }
    }

    return collectionInstance;
}

From source file:com.amalto.core.metadata.ClassRepository.java

private TypeMetadata loadClass(Class clazz) {
    String typeName = getTypeName(clazz);
    if (getType(typeName) != null) { // If already defined return it.
        return getType(typeName);
    } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) {
        return getNonInstantiableType(StringUtils.EMPTY, typeName);
    }/*  w  w  w.  jav a  2s  .co m*/
    entityToJavaClass.put(typeName, clazz);
    if (Map.class.isAssignableFrom(clazz)) {
        return MAP_TYPE;
    }
    if (ArrayListHolder.class.equals(clazz)) {
        typeName = typeName + listCounter++;
    }
    boolean isEntity = typeStack.isEmpty();
    ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity);
    addTypeMetadata(classType);
    typeStack.push(classType);
    String keyFieldName = ""; //$NON-NLS-1$
    if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) {
        SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true,
                "unique-id", //$NON-NLS-1$
                STRING, Collections.<String>emptyList(), Collections.<String>emptyList(),
                Collections.<String>emptyList(), StringUtils.EMPTY);
        keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$
        classType.addField(keyField);
    } else if (isEntity) {
        keyFieldName = "unique-id"; //$NON-NLS-1$
    }
    // Class is abstract / interface: load sub classes
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        Iterable<Class> subClasses = getSubclasses(clazz);
        ComplexTypeMetadata superType = typeStack.peek();
        if (superType.isInstantiable()) {
            typeStack.clear();
        }
        for (Class subClass : subClasses) {
            TypeMetadata typeMetadata = loadClass(subClass);
            typeMetadata.setInstantiable(superType.isInstantiable());
            typeMetadata.addSuperType(superType);
        }
        if (superType.isInstantiable()) {
            typeStack.push(superType);
        }
    }
    // Analyze methods
    Method[] classMethods = getMethods(clazz);
    for (Method declaredMethod : classMethods) {
        if (!Modifier.isStatic(declaredMethod.getModifiers())) {
            if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) {
                String fieldName = getName(declaredMethod);
                if (typeStack.peek().hasField(fieldName)) {
                    continue; // TODO Avoid override of fields (like PK)
                }
                Class<?> returnType = declaredMethod.getReturnType();
                FieldMetadata newField;
                boolean isMany = false;
                boolean isKey = keyFieldName.equals(fieldName);
                if (Iterable.class.isAssignableFrom(returnType)) {
                    returnType = listItemType != null ? listItemType
                            : getListItemClass(declaredMethod, returnType);
                    listItemType = null;
                    isMany = true;
                } else if (ArrayListHolder.class.isAssignableFrom(returnType)) {
                    listItemType = getListItemClass(declaredMethod, returnType);
                    isMany = false;
                } else if (Map.class.isAssignableFrom(returnType)) {
                    isMany = true;
                } else if (returnType.isArray()) {
                    isMany = true;
                    returnType = ((Class) returnType.getComponentType());
                } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$
                    // TODO Serialized XML to string column
                    continue;
                } else if (Class.class.equals(returnType)) {
                    continue;
                } else if (returnType.getPackage() != null
                        && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$
                    continue;
                }
                if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) {
                    String fieldTypeName = returnType.getName().toLowerCase();
                    if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) {
                        fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX);
                    }
                    TypeMetadata fieldType;
                    if (Types.BYTE.equals(fieldTypeName) && isMany) {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                Types.BASE64_BINARY);
                    } else {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName);
                    }
                    newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName,
                            fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(),
                            Collections.<String>emptyList(), StringUtils.EMPTY);
                    LongString annotation = declaredMethod.getAnnotation(LongString.class);
                    if (Types.STRING.equals(fieldTypeName) && annotation != null) {
                        fieldType.setData(MetadataRepository.DATA_MAX_LENGTH,
                                String.valueOf(Integer.MAX_VALUE));
                        if (annotation.preferLongVarchar()) {
                            fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE);
                        }
                    }
                } else {
                    ComplexTypeMetadata fieldType;
                    if (Map.class.isAssignableFrom(returnType)) {
                        fieldType = MAP_TYPE;
                    } else {
                        fieldType = (ComplexTypeMetadata) loadClass(returnType);
                    }
                    if (!isEntity || !fieldType.isInstantiable()) {
                        newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName,
                                new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY);
                    } else {
                        newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName,
                                fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$
                                Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING,
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY);
                    }
                }
                typeStack.peek().addField(newField);
            }
        }
    }

    typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$
            new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
            Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
            StringUtils.EMPTY));

    return typeStack.pop();
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*w w w  . j ava  2s . c  om*/
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
        if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass, key);
        }
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = findTargetClass(key, classMap);
                    targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class || targetType.isInterface()) {
                                    Class targetTypeCopy = targetType;
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                    targetType = targetType == null && targetTypeCopy.isInterface()
                                            ? targetTypeCopy
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    // pd is null
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (beanClass == null || bean instanceof Map
                                    || jsonConfig.getPropertySetStrategy() != null
                                    || !jsonConfig.isIgnorePublicFields()) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:net.sf.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*from ww  w. j a v  a2  s . co m*/
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
        if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass, key);
        }
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = resolveClass(classMap, key, name, type);
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = resolveClass(classMap, key, name, type);
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class || targetType.isInterface()) {
                                    Class targetTypeCopy = targetType;
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                    targetType = targetType == null && targetTypeCopy.isInterface()
                                            ? targetTypeCopy
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (beanClass == null || bean instanceof Map
                                    || jsonConfig.getPropertySetStrategy() != null
                                    || !jsonConfig.isIgnorePublicFields()) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = resolveClass(classMap, key, name, type);
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:net.sf.json.JSONObject.java

private static Class resolveClass(Map classMap, String key, String name, Class type) {
    Class targetClass = findTargetClass(key, classMap);
    if (targetClass == null) {
        targetClass = findTargetClass(name, classMap);
    }/*w ww .ja  va 2 s  .c o  m*/
    if (targetClass == null && type != null) {
        if (List.class.equals(type)) {
            targetClass = ArrayList.class;
        } else if (Map.class.equals(type)) {
            targetClass = LinkedHashMap.class;
        } else if (Set.class.equals(type)) {
            targetClass = LinkedHashSet.class;
        } else if (!type.isInterface() && !Object.class.equals(type)) {
            targetClass = type;
        }
    }
    return targetClass;
}

From source file:com.oembedler.moon.graphql.engine.dfs.GraphQLSchemaDfsTraversal.java

public GraphQLType createGraphQLObjectTypeRecursively(DfsContext dfsContext, final Class<?> implClass) {

    ResolvableTypeAccessor resolvableTypeAccessor = ResolvableTypeAccessor.forClass(implClass);
    String objectName = resolvableTypeAccessor.getName();
    String objectDescription = resolvableTypeAccessor.getDescription();

    GraphQLType graphQLObjectType = objectTypeResolverMap.get(implClass);
    if (!objectTypeNameReferenceMap.containsKey(implClass)) {

        objectTypeNameReferenceMap.put(implClass, objectName);
        objectNameTypeReferenceMap.put(objectName, implClass);

        final List<GraphQLFieldDefinition> graphQLFieldDefinitions = new ArrayList<>();

        if (implClass.isEnum()) {
            graphQLObjectType = buildGraphQLEnumType(dfsContext, resolvableTypeAccessor);
        } else {/*from w w w .ja  va2s.c o m*/

            ReflectionUtils.getAllFields(implClass).forEach(field -> {
                GraphQLFieldDefinition definition = getFieldDefinition(dfsContext, implClass, field);
                if (definition != null)
                    graphQLFieldDefinitions.add(definition);
            });

            ReflectionUtils.getAllMethods(implClass).forEach(method -> {
                GraphQLFieldDefinition definition = getMethodDefinition(dfsContext, implClass, method);
                if (definition != null)
                    graphQLFieldDefinitions.add(definition);
            });

            List<GraphQLType> graphQLInterfaceTypes = Lists.newArrayList();
            if (implClass.isInterface()) {
                if (resolvableTypeAccessor.isGraphQLUnion()) {
                    List<GraphQLType> possibleTypes = new ArrayList<>();
                    for (Class<?> possibleType : resolvableTypeAccessor.getGraphQLUnionPossibleTypes()) {
                        possibleTypes.add(createGraphQLObjectTypeRecursively(dfsContext, possibleType));
                    }

                    graphQLObjectType = GraphQLUnionType.newUnionType().name(resolvableTypeAccessor.getName())
                            .possibleTypes(possibleTypes.toArray(new GraphQLObjectType[possibleTypes.size()]))
                            .typeResolver(new CompleteObjectTreeTypeResolver(objectTypeResolverMap))
                            .description(resolvableTypeAccessor.getDescription()).build();
                    graphQLUnionTypeMap.add((GraphQLUnionType) graphQLObjectType);
                } else {
                    graphQLObjectType = newInterface().name(objectName).description(objectDescription)
                            .fields(graphQLFieldDefinitions)
                            .typeResolver(new CompleteObjectTreeTypeResolver(objectTypeResolverMap)).build();
                }
            } else {
                ClassUtils.getAllInterfacesForClassAsSet(implClass).forEach(aClass -> {
                    if (isAcceptableInterface(dfsContext, aClass)) {
                        GraphQLType graphQLType = createGraphQLObjectTypeRecursively(dfsContext, aClass);
                        graphQLInterfaceTypes.add(graphQLType);
                    }
                });

                graphQLObjectType = newObject().name(objectName).description(objectDescription)
                        .fields(graphQLFieldDefinitions)
                        .withInterfaces(resolveInterfaceReferences(dfsContext, graphQLInterfaceTypes)).build();
            }
        }

        objectTypeResolverMap.put(implClass, graphQLObjectType);
    } else {
        // reference
        //if (!implClass.isInterface())
        graphQLObjectType = new GraphQLTypeReference(objectName);
    }
    return graphQLObjectType;
}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

/**
 * ?/*w  w w . j a  v  a 2  s.c om*/
 * 
 * @param method
 * @return
 */
public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) {
    if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type)
            || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type)
            || URL.class.isAssignableFrom(type)) {
        // 
        return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.",
                "");
    } // end if

    if (type.isArray()) {
        // 
        return new Object[] {
                buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) };
    } // end if

    if (ClassUtils.isAssignable(Map.class, type)) {
        // Map
        return Map.class.getName();
    } // end if

    if (type.isEnum()) {
        // Enum
        return Enum.class.getName();
    } // end if

    boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false;

    if (isCollection) {

        Type rawType = type;
        if (genericType != null) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType _type = (ParameterizedType) genericType;
                Type[] actualTypeArguments = _type.getActualTypeArguments();
                rawType = actualTypeArguments[0];

            } else if (genericType instanceof GenericArrayType) {
                rawType = ((GenericArrayType) genericType).getGenericComponentType();
            }

            if (genericType instanceof WildcardType) {
                rawType = ((WildcardType) genericType).getUpperBounds()[0];
            }
        }

        if (rawType == type) {

            return new Object[] { rawType.getClass().getName() };
        } else {

            if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) {
                return new Object[] { buildTypeStructure(
                        (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType,
                        genericType) };
            } else {
                if (rawType instanceof ParameterizedType) {
                    if (((ParameterizedType) rawType).getRawType() == Map.class) {
                        return new Object[] { Map.class.getName() };
                    }
                }
                if (oriGenericType == rawType) {
                    return new Object[] { rawType.getClass().getName() };
                }
                return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) };
            }
        }
    }

    if (type.isInterface()) {
        return type.getName();
    }

    ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName());
    //added 
    if (null == paramClassInfo) {
        System.out.println("failed to get paramClassInfo for :" + type.getName());
        return null;
    }

    List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>();

    BeanWrapper bean = new BeanWrapperImpl(type);

    PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors();
    Method readMethod;

    String name;

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        readMethod = propertyDescriptor.getReadMethod();

        if (readMethod == null || "getClass".equals(readMethod.getName())) {
            continue;
        }

        name = propertyDescriptor.getName();

        FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name);
        if (readMethod.getReturnType().isAssignableFrom(type)) {
            String comment = "structure is the same with parent.";
            typeConstructure
                    .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment));
        } else {
            typeConstructure.add(
                    FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure(
                            readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType)));
        } // end if
    }

    return typeConstructure;
}