Example usage for java.lang Class getDeclaredAnnotations

List of usage examples for java.lang Class getDeclaredAnnotations

Introduction

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

Prototype

public Annotation[] getDeclaredAnnotations() 

Source Link

Usage

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

@Override
public void fileChanged(FileChangeEvent arg0) throws Exception {
    try {//from  w  w  w  .j a  v a2 s .c  o  m
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            fileDeleted(arg0);
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (cls.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : cls) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), 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("/", "."));
                    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) {
                                    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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
            System.out.println(baseFile.getName().getURI() + " Deployed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

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

@Override
public void fileCreated(FileChangeEvent arg0) throws Exception {
    try {/* w ww.j  a v a  2s.c  o m*/
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            System.out.println(baseFile.getName().getURI());
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> clsStateless = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (clsStateless.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : clsStateless) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), 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("/", "."));
                    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) {
                                    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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
        }
        System.out.println(baseFile.getName().getURI() + " Deployed");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

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

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;//from   www.  j  av a  2 s .  co  m
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            Thread.currentThread().getContextClassLoader());
                    ConfigurationBuilder config = new ConfigurationBuilder();
                    config.addUrls(ClasspathHelper.forClassLoader(classLoader));
                    config.addClassLoader(classLoader);
                    org.reflections.Reflections reflections = new org.reflections.Reflections(config);
                    EJBContainer container = EJBContainer
                            .getInstance("file:///" + scanJarFile.getAbsolutePath(), config);
                    container.inject();
                    Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
                    Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
                    Object obj;
                    System.gc();
                    if (cls.size() > 0) {
                        ejbContext = new EJBContext();
                        ejbContext.setJarPath(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        for (Class<?> ejbInterface : cls) {
                            //BeanPool.getInstance().create(ejbInterface);
                            obj = BeanPool.getInstance().get(ejbInterface);
                            System.out.println(obj);
                            ProxyFactory factory = new ProxyFactory();
                            obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                                    servicesRegistryPort);
                            String remoteBinding = container.getRemoteBinding(ejbInterface);
                            System.out.println(remoteBinding + " for EJB" + obj);
                            if (remoteBinding != null) {
                                //registry.unbind(remoteBinding);
                                registry.rebind(remoteBinding, (Remote) obj);
                                ejbContext.put(remoteBinding, obj.getClass());
                            }
                            //registry.rebind("name", (Remote) obj);
                        }
                        jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    System.out.println("Class Message Driven" + clsMessageDriven);
                    if (clsMessageDriven.size() > 0) {
                        System.out.println("Class Message Driven");
                        MDBContext mdbContext;
                        ConcurrentHashMap<String, MDBContext> mdbContexts;
                        if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                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("/", "."));
                            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) {
                                            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) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    classLoader.close();
                    System.out.println(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

From source file:com.espertech.esper.dataflow.core.DataFlowServiceImpl.java

private Map<Integer, OperatorMetadataDescriptor> resolveMetadata(CreateDataFlowDesc graphDesc,
        EPDataFlowInstantiationOptions options, EngineImportService engineImportService,
        Map<GraphOperatorSpec, Annotation[]> operatorAnnotations) throws ExprValidationException {
    Map<Integer, OperatorMetadataDescriptor> operatorClasses = new HashMap<Integer, OperatorMetadataDescriptor>();
    for (int i = 0; i < graphDesc.getOperators().size(); i++) {
        GraphOperatorSpec operatorSpec = graphDesc.getOperators().get(i);
        String operatorPrettyPrint = toPrettyPrint(i, operatorSpec);
        Annotation[] operatorAnnotation = operatorAnnotations.get(operatorSpec);

        // see if the operator is already provided by options
        if (options.getOperatorProvider() != null) {
            Object operator = options.getOperatorProvider().provide(new EPDataFlowOperatorProviderContext(
                    graphDesc.getGraphName(), operatorSpec.getOperatorName(), operatorSpec));
            if (operator != null) {
                OperatorMetadataDescriptor descriptor = new OperatorMetadataDescriptor(operatorSpec, i,
                        operator.getClass(), null, operator, operatorPrettyPrint, operatorAnnotation);
                operatorClasses.put(i, descriptor);
                continue;
            }//from  ww  w.j  a  v a2  s  .  co  m
        }

        // try to find factory class with factory annotation
        Class factoryClass = null;
        try {
            factoryClass = engineImportService.resolveClass(operatorSpec.getOperatorName() + "Factory");
        } catch (EngineImportException e) {
        }

        // if the factory implements the interface use that
        if (factoryClass != null
                && JavaClassHelper.isImplementsInterface(factoryClass, DataFlowOperatorFactory.class)) {
            OperatorMetadataDescriptor descriptor = new OperatorMetadataDescriptor(operatorSpec, i, null,
                    factoryClass, null, operatorPrettyPrint, operatorAnnotation);
            operatorClasses.put(i, descriptor);
            continue;
        }

        // resolve by class name
        Class clazz;
        try {
            clazz = engineImportService.resolveClass(operatorSpec.getOperatorName());
        } catch (EngineImportException e) {
            throw new ExprValidationException(
                    "Failed to resolve operator '" + operatorSpec.getOperatorName() + "': " + e.getMessage(),
                    e);
        }

        if (!JavaClassHelper.isImplementsInterface(clazz, DataFlowSourceOperator.class) && !JavaClassHelper
                .isAnnotationListed(DataFlowOperator.class, clazz.getDeclaredAnnotations())) {
            throw new ExprValidationException("Failed to resolve operator '" + operatorSpec.getOperatorName()
                    + "', operator class " + clazz.getName() + " does not declare the "
                    + DataFlowOperator.class.getSimpleName() + " annotation or implement the "
                    + DataFlowSourceOperator.class.getSimpleName() + " interface");
        }

        OperatorMetadataDescriptor descriptor = new OperatorMetadataDescriptor(operatorSpec, i, clazz, null,
                null, operatorPrettyPrint, operatorAnnotation);
        operatorClasses.put(i, descriptor);
    }
    return operatorClasses;
}

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

public void deployEjbJar(URL url, StandardFileSystemManager manager, ClassLoader cL) {
    try {/* w w w. j  av  a  2  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:org.apache.openjpa.persistence.jdbc.AnnotationPersistenceMappingParser.java

@Override
protected void parseClassMappingAnnotations(ClassMetaData meta) {
    ClassMapping cm = (ClassMapping) meta;
    Class<?> cls = cm.getDescribedType();

    MappingTag tag;//from   w  w w  . j  a va 2  s .c o  m
    for (Annotation anno : cls.getDeclaredAnnotations()) {
        tag = _tags.get(anno.annotationType());
        if (tag == null) {
            handleUnknownClassMappingAnnotation(cm, anno);
            continue;
        }

        switch (tag) {
        case ASSOC_OVERRIDE:
            parseAssociationOverrides(cm, (AssociationOverride) anno);
            break;
        case ASSOC_OVERRIDES:
            parseAssociationOverrides(cm, ((AssociationOverrides) anno).value());
            break;
        case ATTR_OVERRIDE:
            parseAttributeOverrides(cm, (AttributeOverride) anno);
            break;
        case ATTR_OVERRIDES:
            parseAttributeOverrides(cm, ((AttributeOverrides) anno).value());
            break;
        case DISCRIM_COL:
            parseDiscriminatorColumn(cm, (DiscriminatorColumn) anno);
            break;
        case DISCRIM_VAL:
            cm.getDiscriminator().getMappingInfo().setValue(((DiscriminatorValue) anno).value());
            if (Modifier.isAbstract(cm.getDescribedType().getModifiers()) && getLog().isInfoEnabled()) {
                getLog().info(_loc.get("discriminator-on-abstract-class", cm.getDescribedType().getName()));
            }
            break;
        case INHERITANCE:
            parseInheritance(cm, (Inheritance) anno);
            break;
        case PK_JOIN_COL:
            parsePrimaryKeyJoinColumns(cm, (PrimaryKeyJoinColumn) anno);
            break;
        case PK_JOIN_COLS:
            parsePrimaryKeyJoinColumns(cm, ((PrimaryKeyJoinColumns) anno).value());
            break;
        case SECONDARY_TABLE:
            parseSecondaryTables(cm, (SecondaryTable) anno);
            break;
        case SECONDARY_TABLES:
            parseSecondaryTables(cm, ((SecondaryTables) anno).value());
            break;
        case SQL_RESULT_SET_MAPPING:
            parseSQLResultSetMappings(cm, (SqlResultSetMapping) anno);
            break;
        case SQL_RESULT_SET_MAPPINGS:
            parseSQLResultSetMappings(cm, ((SqlResultSetMappings) anno).value());
            break;
        case TABLE:
            parseTable(cm, (Table) anno);
            break;
        case TABLE_GEN:
            parseTableGenerator(cls, (TableGenerator) anno);
            break;
        case DATASTORE_ID_COL:
            parseDataStoreIdColumn(cm, (DataStoreIdColumn) anno);
            break;
        case DISCRIM_STRAT:
            cm.getDiscriminator().getMappingInfo().setStrategy(((DiscriminatorStrategy) anno).value());
            break;
        case FK:
            parseForeignKey(cm.getMappingInfo(), (ForeignKey) anno);
            break;
        case MAPPING_OVERRIDE:
            parseMappingOverrides(cm, (MappingOverride) anno);
            break;
        case MAPPING_OVERRIDES:
            parseMappingOverrides(cm, ((MappingOverrides) anno).value());
            break;
        case STRAT:
            cm.getMappingInfo().setStrategy(((Strategy) anno).value());
            break;
        case SUBCLASS_FETCH_MODE:
            cm.setSubclassFetchMode(toEagerFetchModeConstant(((SubclassFetchMode) anno).value()));
            break;
        case VERSION_COL:
            parseVersionColumns(cm, (VersionColumn) anno);
            break;
        case VERSION_COLS:
            parseVersionColumns(cm, ((VersionColumns) anno).value());
            break;
        case VERSION_STRAT:
            cm.getVersion().getMappingInfo().setStrategy(((VersionStrategy) anno).value());
            break;
        case X_MAPPING_OVERRIDE:
            parseMappingOverrides(cm, (XMappingOverride) anno);
            break;
        case X_MAPPING_OVERRIDES:
            parseMappingOverrides(cm, ((XMappingOverrides) anno).value());
            break;
        case X_TABLE:
        case X_SECONDARY_TABLE:
        case X_SECONDARY_TABLES:
            // no break; not supported yet
        case STOREDPROCEDURE_QUERIES:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedStoredProcedureQueries(_cls, ((NamedStoredProcedureQueries) anno).value());
            break;
        case STOREDPROCEDURE_QUERY:
            if (isQueryMode() && (meta.getSourceMode() & MODE_QUERY) == 0)
                parseNamedStoredProcedureQueries(_cls, ((NamedStoredProcedureQuery) anno));
            break;
        default:
            throw new UnsupportedException(_loc.get("unsupported", cm, anno));
        }
    }
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

public void initRuleTemplate(RuleTemplate ruleTemplate, InitializerContext initializerContext)
        throws Exception {
    TypeInfo typeInfo = TypeInfo.parse(ruleTemplate.getType());
    if (typeInfo == null) {
        return;//from   www  .  j  ava 2 s .c  o  m
    }

    Class<?> type = typeInfo.getType();
    RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager();
    ruleTemplate.setAbstract(Modifier.isAbstract(type.getModifiers()));

    // ??SuperType?ParentTemplate
    Class<?> superType = type.getSuperclass();
    List<Class<?>> superTypes = new ArrayList<Class<?>>();
    while (superType != null && !superType.equals(Object.class)
            && !superType.equals(ClientEventSupportedObject.class)) {
        RuleTemplate parentRuleTemplate = ruleTemplateManager.getRuleTemplate(superType);
        if (parentRuleTemplate != null) {
            if (superTypes.isEmpty()) {
                ruleTemplate.setParents(new RuleTemplate[] { parentRuleTemplate });
            }
            break;
        }
        superTypes.add(superType);
        superType = superType.getSuperclass();
    }

    // ?AbstractParentTemplate
    RuleTemplate parentRuleTemplate = null;
    if (!superTypes.isEmpty()) {
        for (int i = superTypes.size() - 1; i >= 0; i--) {
            superType = superTypes.get(i);
            RuleTemplate newRuleTemplate = createRuleTemplate(ruleTemplateManager, superType,
                    parentRuleTemplate);
            parentRuleTemplate = newRuleTemplate;
        }
        if (parentRuleTemplate != null && ruleTemplate.getParents() == null) {
            ruleTemplate.setParents(new RuleTemplate[] { parentRuleTemplate });
        }
    }

    XmlNodeInfo xmlNodeInfo = getXmlNodeInfo(type);

    String scope = xmlNodeInfo.getScope();
    if (StringUtils.isEmpty(scope) && Component.class.isAssignableFrom(type)) {
        Widget widget = type.getAnnotation(Widget.class);
        boolean isDeclaredAnnotation = (widget != null
                && ArrayUtils.indexOf(type.getDeclaredAnnotations(), widget) >= 0);
        if (widget != null && !ruleTemplate.isAbstract()) {
            if (StringUtils.isNotEmpty(widget.name()) && !widget.name().equals(ruleTemplate.getName())
                    && (isDeclaredAnnotation || !AssembledComponent.class.isAssignableFrom(type))) {
                ruleTemplate.setLabel(widget.name());
            }
        }
        if (!(widget != null && isDeclaredAnnotation && !Modifier.isAbstract(type.getModifiers()))) {
            scope = "protected";
        }
    }
    if (StringUtils.isNotEmpty(scope) && StringUtils.isEmpty(ruleTemplate.getScope())) {
        ruleTemplate.setScope(scope);
    }

    String nodeName = xmlNodeInfo.getNodeName();
    if (StringUtils.isNotEmpty(nodeName)) {
        ruleTemplate.setNodeName(nodeName);
    }

    if (StringUtils.isEmpty(ruleTemplate.getLabel())) {
        String label = xmlNodeInfo.getLabel();
        if (StringUtils.isNotEmpty(label)) {
            ruleTemplate.setLabel(label);
        } else if (!ruleTemplate.isAbstract()) {
            ruleTemplate.setLabel(type.getSimpleName());
        }
    }

    if (StringUtils.isNotEmpty(xmlNodeInfo.getIcon())) {
        ruleTemplate.setIcon(xmlNodeInfo.getIcon());
    }

    int clientTypes = ClientType.parseClientTypes(xmlNodeInfo.getClientTypes());
    if (clientTypes > 0) {
        ruleTemplate.setClientTypes(clientTypes);
    } else if (Control.class.isAssignableFrom(type) && "public".equals(ruleTemplate.getScope())) {
        ruleTemplate.setClientTypes(ClientType.DESKTOP);
    }

    if (!ruleTemplate.isDeprecated() && xmlNodeInfo.isDeprecated()) {
        ruleTemplate.setDeprecated(true);
    }

    IdeObject ideObject = type.getAnnotation(IdeObject.class);
    if (ideObject != null && ArrayUtils.indexOf(type.getDeclaredAnnotations(), ideObject) >= 0) {
        if (StringUtils.isNotEmpty(ideObject.labelProperty())) {
            ruleTemplate.setLabelProperty(ideObject.labelProperty());
        }
        ruleTemplate.setVisible(ideObject.visible());
    }

    // search icon
    if (ruleTemplate.getIcon() == null) {
        String basePath = '/' + StringUtils.replaceChars(type.getName(), '.', '/'), iconPath;

        iconPath = basePath + ".png";
        if (getClass().getResource(iconPath) != null) {
            ruleTemplate.setIcon(iconPath);
        } else {
            iconPath = basePath + ".gif";
            if (getClass().getResource(iconPath) != null) {
                ruleTemplate.setIcon(iconPath);
            }
        }
    }

    if (Component.class.isAssignableFrom(type)) {
        Widget widget = type.getAnnotation(Widget.class);
        if (widget != null) {
            if (ArrayUtils.indexOf(type.getDeclaredAnnotations(), widget) >= 0) {
                if (StringUtils.isEmpty(ruleTemplate.getCategory())) {
                    ruleTemplate.setCategory(widget.category());
                }
                ruleTemplate.setAutoGenerateId(widget.autoGenerateId());
            }
        }
    }

    List<String> robots = null;
    Map<String, RobotInfo> robotMap = robotRegistry.getRobotMap();
    for (Map.Entry<String, RobotInfo> entry : robotMap.entrySet()) {
        RobotInfo robotInfo = entry.getValue();
        if (robotInfo != null) {
            String pattern = robotInfo.getViewObject();
            if (PathUtils.match(pattern, ruleTemplate.getName())) {
                if (robots == null) {
                    robots = new ArrayList<String>();
                }
                robots.add(robotInfo.getName() + '|' + robotInfo.getLabel());
            }
        }
    }

    if (robots != null) {
        ruleTemplate.setRobots(robots.toArray(new String[0]));
    }

    initProperties(ruleTemplate, typeInfo, xmlNodeInfo, initializerContext);
    initChildTemplates(ruleTemplate, typeInfo, xmlNodeInfo, initializerContext);
    initClientEvent(ruleTemplate, typeInfo, initializerContext);

    if (xmlNodeInfo != null && !xmlNodeInfo.getImplTypes().isEmpty()) {
        Set<Class<?>> implTypes = ClassUtils.findClassTypes(xmlNodeInfo.getImplTypes().toArray(new String[0]),
                type);
        for (Class<?> implType : implTypes) {
            if (implType.equals(type)) {
                continue;
            }

            if (ruleTemplateManager.getRuleTemplate(implType) == null) {
                // ?parentRuleTemplate??RuleTemplateinit?
                createRuleTemplate(ruleTemplateManager, implType, null);
            }
        }
    }
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype)
        throws PersistenceException {
    LookupDelegate delegate = getLookupDelegate(fieldName);

    if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) {
        throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid.");
    }//from   w ww  . j a v  a  2 s . com
    try {
        if (toType.equals(String.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof String)) {
                dataStoreValue = dataStoreValue.toString();
            }
        } else if (Enum.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null) {
                Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString());

                dataStoreValue = e;
            }
        } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) {
            if (dataStoreValue == null) {
                dataStoreValue = false;
            } else if (!(dataStoreValue instanceof Boolean)) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    dataStoreValue = (((Number) dataStoreValue).intValue() != 0);
                } else {
                    dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true")
                            || dataStoreValue.toString().trim().equalsIgnoreCase("y"));
                }
            }
        } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class)
                || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class)
                || toType.equals(float.class) || toType.equals(double.class)) {
            if (dataStoreValue == null) {
                if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) {
                    dataStoreValue = 0;
                } else if (toType.equals(float.class) || toType.equals(double.class)) {
                    dataStoreValue = 0.0f;
                }
            } else if (toType.equals(Number.class)) {
                if (!(dataStoreValue instanceof Number)) {
                    if (dataStoreValue instanceof String) {
                        try {
                            dataStoreValue = Double.parseDouble((String) dataStoreValue);
                        } catch (NumberFormatException e) {
                            throw new PersistenceException("Unable to map " + fieldName + " as " + toType
                                    + " using " + dataStoreValue);
                        }
                    } else if (dataStoreValue instanceof Boolean) {
                        dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                    } else {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                }
            } else if (toType.equals(Integer.class) || toType.equals(int.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Integer)) {
                        dataStoreValue = ((Number) dataStoreValue).intValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Integer.parseInt((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Long.class) || toType.equals(long.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Long)) {
                        dataStoreValue = ((Number) dataStoreValue).longValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Long.parseLong((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Byte.class) || toType.equals(byte.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Byte)) {
                        dataStoreValue = ((Number) dataStoreValue).byteValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Byte.parseByte((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Short.class) || toType.equals(short.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Short)) {
                        dataStoreValue = ((Number) dataStoreValue).shortValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Short.parseShort((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Double.class) || toType.equals(double.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Double)) {
                        dataStoreValue = ((Number) dataStoreValue).doubleValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Double.parseDouble((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Float.class) || toType.equals(float.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Float)) {
                        dataStoreValue = ((Number) dataStoreValue).floatValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Float.parseFloat((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigDecimal.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigDecimal)) {
                        if (dataStoreValue instanceof BigInteger) {
                            dataStoreValue = new BigDecimal((BigInteger) dataStoreValue);
                        } else {
                            dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigInteger.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigInteger)) {
                        if (dataStoreValue instanceof BigDecimal) {
                            dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger();
                        } else {
                            dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (dataStoreValue != null) {
                logger.error("Type of dataStoreValue=" + dataStoreValue.getClass());
                throw new PersistenceException(
                        "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
            }
        } else if (toType.equals(Locale.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) {
                String[] parts = dataStoreValue.toString().split("_");

                if (parts != null && parts.length > 1) {
                    dataStoreValue = new Locale(parts[0], parts[1]);
                } else {
                    dataStoreValue = new Locale(parts[0]);
                }
            }
        } else if (Measured.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null && ptype != null) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    Constructor<? extends Measured> constructor = null;
                    double value = ((Number) dataStoreValue).doubleValue();

                    for (Constructor<?> c : toType.getDeclaredConstructors()) {
                        Class[] args = c.getParameterTypes();

                        if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0])
                                && UnitOfMeasure.class.isAssignableFrom(args[1])) {
                            constructor = (Constructor<? extends Measured>) c;
                            break;
                        }
                    }
                    if (constructor == null) {
                        throw new PersistenceException("Unable to map with no proper constructor");
                    }
                    dataStoreValue = constructor.newInstance(value,
                            ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                } else if (!(dataStoreValue instanceof Measured)) {
                    try {
                        dataStoreValue = Double.parseDouble(dataStoreValue.toString());
                    } catch (NumberFormatException e) {
                        Method method = null;

                        for (Method m : toType.getDeclaredMethods()) {
                            if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) {
                                if (m.getParameterTypes().length == 1
                                        && m.getParameterTypes()[0].equals(String.class)) {
                                    method = m;
                                    break;
                                }
                            }
                        }
                        if (method == null) {
                            throw new PersistenceException("Don't know how to map " + dataStoreValue + " to "
                                    + toType + "<" + ptype + ">");
                        }
                        dataStoreValue = method.invoke(null, dataStoreValue.toString());
                    }
                }
                // just because we converted it to a measured object above doesn't mean
                // we have the unit of measure right
                if (dataStoreValue instanceof Measured) {
                    UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0])
                            .newInstance();

                    if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) {
                        dataStoreValue = ((Measured) dataStoreValue).convertTo(
                                (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                    }
                }
            }
        } else if (toType.equals(UUID.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) {
                dataStoreValue = UUID.fromString(dataStoreValue.toString());
            }
        } else if (toType.equals(TimeZone.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) {
                dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString());
            }
        } else if (toType.equals(Currency.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) {
                dataStoreValue = Currency.getInstance(dataStoreValue.toString());
            }
        } else if (toType.isArray()) {
            Class<?> t = toType.getComponentType();

            if (dataStoreValue == null) {
                dataStoreValue = Array.newInstance(t, 0);
            } else if (dataStoreValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) dataStoreValue;

                if (long.class.isAssignableFrom(t)) {
                    long[] replacement = (long[]) Array.newInstance(long.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (int.class.isAssignableFrom(t)) {
                    int[] replacement = (int[]) Array.newInstance(int.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (float.class.isAssignableFrom(t)) {
                    float[] replacement = (float[]) Array.newInstance(float.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (double.class.isAssignableFrom(t)) {
                    double[] replacement = (double[]) Array.newInstance(double.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (boolean.class.isAssignableFrom(t)) {
                    boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else {
                    Object[] replacement = (Object[]) Array.newInstance(t, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                }
            } else if (!dataStoreValue.getClass().isArray()) {
                logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to "
                        + toType.getName());
                logger.error("Value of " + fieldName + "=" + dataStoreValue);
                throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName());
            }
        } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) {
            Annotation[] alist = toType.getDeclaredAnnotations();
            boolean autoJSON = false;

            for (Annotation a : alist) {
                if (a instanceof AutoJSON) {
                    autoJSON = true;
                }
            }
            if (autoJSON) {
                dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue);
            } else {
                try {
                    Method m = toType.getDeclaredMethod("valueOf", JSONObject.class);

                    dataStoreValue = m.invoke(null, dataStoreValue);
                } catch (NoSuchMethodException ignore) {
                    try {
                        Method m = toType.getDeclaredMethod("valueOf", String.class);

                        if (m != null) {
                            dataStoreValue = m.invoke(null, dataStoreValue.toString());
                        } else {
                            throw new PersistenceException(
                                    "No valueOf() field in " + toType + " for mapping " + fieldName);
                        }
                    } catch (NoSuchMethodException e) {
                        throw new PersistenceException("No valueOf() field in " + toType + " for mapping "
                                + fieldName + " with " + dataStoreValue + ": ("
                                + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")");
                    }
                }
            }
        }
    } catch (Exception e) {
        String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage();
        logger.error(err, e);
        throw new PersistenceException();
    }
    return dataStoreValue;
}