Search in sources :

Example 31 with InitialContext

use of javax.naming.InitialContext in project jetty.project by eclipse.

the class ResourceAnnotationHandler method handleMethod.

/**
     * Process a Resource annotation on a Method.
     * <p>
     * This will generate a JNDI entry, and an Injection to be
     * processed when an instance of the class is created.
     * 
     * @param clazz the class to process 
     * @param method the method to process
     */
public void handleMethod(Class<?> clazz, Method method) {
    Resource resource = (Resource) method.getAnnotation(Resource.class);
    if (resource != null) {
        //JavaEE Spec 5.2.3: Method cannot be static
        if (Modifier.isStatic(method.getModifiers())) {
            LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": cannot be static");
            return;
        }
        // only 1 parameter
        if (!method.getName().startsWith("set")) {
            LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, does not start with 'set'");
            return;
        }
        if (method.getParameterCount() != 1) {
            LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, not single argument to method");
            return;
        }
        if (Void.TYPE != method.getReturnType()) {
            LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, not void");
            return;
        }
        //default name is the javabean property name
        String name = method.getName().substring(3);
        name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
        name = clazz.getCanonicalName() + "/" + name;
        name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name);
        String mappedName = (resource.mappedName() != null && !resource.mappedName().trim().equals("") ? resource.mappedName() : null);
        Class<?> paramType = method.getParameterTypes()[0];
        Class<?> resourceType = resource.type();
        //Servlet Spec 3.0 p. 76
        //If a descriptor has specified at least 1 injection target for this
        //resource, then it overrides this annotation
        MetaData metaData = _context.getMetaData();
        if (metaData.getOriginDescriptor("resource-ref." + name + ".injection") != null) {
            //it overrides this annotation
            return;
        }
        //check if an injection has already been setup for this target by web.xml
        InjectionCollection injections = (InjectionCollection) _context.getAttribute(InjectionCollection.INJECTION_COLLECTION);
        if (injections == null) {
            injections = new InjectionCollection();
            _context.setAttribute(InjectionCollection.INJECTION_COLLECTION, injections);
        }
        Injection injection = injections.getInjection(name, clazz, method, paramType);
        if (injection == null) {
            try {
                //try binding name to environment
                //try the webapp's environment first
                boolean bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context, name, mappedName);
                //try the server's environment
                if (!bound)
                    bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name, mappedName);
                //try the jvm's environment
                if (!bound)
                    bound = org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(null, name, mappedName);
                //NamingEntry, just a value bound in java:comp/env
                if (!bound) {
                    try {
                        InitialContext ic = new InitialContext();
                        String nameInEnvironment = (mappedName != null ? mappedName : name);
                        ic.lookup("java:comp/env/" + nameInEnvironment);
                        bound = true;
                    } catch (NameNotFoundException e) {
                        bound = false;
                    }
                }
                if (bound) {
                    LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name);
                    //   Make the Injection for it
                    injection = new Injection();
                    injection.setTarget(clazz, method, paramType, resourceType);
                    injection.setJndiName(name);
                    injection.setMappingName(mappedName);
                    injections.add(injection);
                    //TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination
                    metaData.setOrigin("resource-ref." + name + ".injection", resource, clazz);
                } else if (!isEnvEntryType(paramType)) {
                    // JavaEE Spec. sec 5.4.1.3
                    throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName));
                }
            } catch (NamingException e) {
                // JavaEE Spec. sec 5.4.1.3
                if (!isEnvEntryType(paramType))
                    throw new IllegalStateException(e);
            }
        }
    }
}
Also used : InjectionCollection(org.eclipse.jetty.plus.annotation.InjectionCollection) NameNotFoundException(javax.naming.NameNotFoundException) MetaData(org.eclipse.jetty.webapp.MetaData) Resource(javax.annotation.Resource) NamingException(javax.naming.NamingException) Injection(org.eclipse.jetty.plus.annotation.Injection) InitialContext(javax.naming.InitialContext)

Example 32 with InitialContext

use of javax.naming.InitialContext in project jBPM5-Developer-Guide by Salaboy.

the class PersistentProcessTest method processInstancesAndLocalHTPlusFailTest.

@Test
public void processInstancesAndLocalHTPlusFailTest() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("process-async-interactions.bpmn"), ResourceType.BPMN2);
    if (kbuilder.hasErrors()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            System.out.println(">>> Error:" + error.getMessage());
        }
        fail(">>> Knowledge couldn't be parsed! ");
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    Environment env = EnvironmentFactory.newEnvironment();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.runtime.ht");
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());
    // Let's create a Persistence Knowledge Session
    System.out.println(" >>> Let's create a Persistent Knowledge Session");
    final StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int sessionId = ksession.getId();
    assertNotNull(sessionId);
    assertTrue(sessionId != 0);
    // We need to register the WorkItems and Listeners that the session will use
    TaskService client = createTaskService(emf);
    LocalHTWorkItemHandler localHTWorkItemHandler = new LocalHTWorkItemHandler(client, ksession);
    MockFaultWorkItemHandler mockFaultWorkItemHandler = new MockFaultWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", localHTWorkItemHandler);
    ksession.getWorkItemManager().registerWorkItemHandler("External Service Call", mockFaultWorkItemHandler);
    //KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
    // Let's create a Process Instance
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    //Each Command will generate an interaction
    System.out.println(">>> Let's Create Process Instance");
    ProcessInstance processInstance = ksession.createProcessInstance("com.salaboy.process.AsyncInteractions", params);
    System.out.println(">>> Let's Start the Process Instance");
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.startProcessInstance(processInstance.getId());
    ut.commit();
    System.out.println(" >>> Looking for Salaboy's Tasks");
    List<TaskSummary> salaboysTasks = client.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");
    assertTrue(salaboysTasks.size() == 1);
    TaskSummary salaboyTask = salaboysTasks.get(0);
    System.out.println(" >>> Starting Salaboy's Task");
    client.start(salaboyTask.getId(), "salaboy");
    System.out.println(" >>> Completing Salaboy's Task");
    ut.begin();
    try {
        client.complete(salaboyTask.getId(), "salaboy", null);
        ut.commit();
    } catch (WorkflowRuntimeException e) {
        System.out.println("Rolling back transaction" + e);
        ut.rollback();
    }
    System.out.println(" >>> Looking for Salaboy's Tasks");
    Task salaboysTask = client.getTask(salaboyTask.getId());
    assertNotNull(salaboysTask);
    assertEquals("InProgress", salaboysTask.getTaskData().getStatus().name());
    // We need to dispose the session, because the reference to this ksession object will no longer be valid
    //  because another thread could load the same session and execute a different command.
    System.out.println(" >>> Disposing Session");
    ksession.dispose();
}
Also used : UserTransaction(javax.transaction.UserTransaction) KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) Task(org.jbpm.task.Task) HashMap(java.util.HashMap) LocalTaskService(org.jbpm.task.service.local.LocalTaskService) TaskService(org.jbpm.task.TaskService) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) ClassPathResource(org.drools.io.impl.ClassPathResource) InitialContext(javax.naming.InitialContext) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) KnowledgeBase(org.drools.KnowledgeBase) EntityManagerFactory(javax.persistence.EntityManagerFactory) TaskSummary(org.jbpm.task.query.TaskSummary) ProcessInstance(org.drools.runtime.process.ProcessInstance) Person(com.salaboy.model.Person) LocalHTWorkItemHandler(org.jbpm.process.workitem.wsht.LocalHTWorkItemHandler)

Example 33 with InitialContext

use of javax.naming.InitialContext in project jBPM5-Developer-Guide by Salaboy.

the class SingleSessionPatternsTest method singleSessionPerProcessDefinitionWithRules.

/**
     * This test uses a single session to start all the instances of a process 
     * definition. The singularity of the test is that it never starts a process
     * instance directly. Instead of that the session uses a rule to determine
     * when a process instance must be started.
     * @throws Exception 
     */
@Test
public void singleSessionPerProcessDefinitionWithRules() throws Exception {
    //Creates an entity manager and get the user transaction. We are going
    //to need them later to interact with the business entities persisted
    //by the work item handlers we have configured in our session.
    EntityManager em = getEmf().createEntityManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    //Creates the ksession. In this case the ksession
    //will not only contains the process definition but it is also going to
    //have a rule that is going to start a process instance for each
    //Person object we insert in the session.
    StatefulKnowledgeSession ksession = createProcessWithRulesKnowledgeSession("myProcessDefinitionSession");
    registerWorkItemHandlers(ksession, "myProcessDefinitionSession", em);
    //Instead of manually starting a new process instance we will let the
    //rules to start it when they consider it is necessary.
    //In this case we are going to instantiate a Person object and insert it
    //into the session. After this we will call ksession.fireAllRules() to
    //execute any activated rule.
    Person person = new Person("Salaboy", 29);
    ksession.insert(person);
    ksession.fireAllRules();
    //Dispose the session since we are no longer interested in it.
    ksession.dispose();
    //At this point, a process instance must be started and we should have
    //a business entity persisted in the database. Remember that this entity
    //was persisted by the work item hanlder we have configured for our tasks.
    BusinessEntity businessEntity = getBusinessEntity("myProcessDefinitionSession", em);
    Assert.assertNotNull(businessEntity);
    //Let's restore the session now to insert a new instance of Person and
    //see what happens. In order to restore the session we are using the
    //sessionId present in the business entity we have retrieved from the 
    //database.
    ksession = loadKnowldgeSession(businessEntity.getSessionId(), "myProcessDefinitionSession", em);
    assertNotNull(ksession);
    //Let's create a new Person and insert it in the sesssion. This will
    //cause a new process instance to be launched.
    Person person2 = new Person("Salaboy", 29);
    ksession.insert(person2);
    ksession.fireAllRules();
    //Dispose the session since we are no longer interested in it.
    ksession.dispose();
    //Getting the correct work item to finish:
    //If we don't know which workItem do we want to complete we can create 
    //a query to see which are pending work items for a process or for a 
    //more complex business key.
    //If the thread that wants to notify the engine about the completion of 
    //the external interaction is the one which has created the token inside 
    //the WorkItemHandler it can use that unique value to get the related 
    //workItemId.
    BusinessEntity businessEntityByWorkItemId = getBusinessEntityByWorkItemId(1L, em);
    //Before completing the work item we need to reload the session once again.
    ksession = loadKnowldgeSession(businessEntityByWorkItemId.getSessionId(), "myProcessDefinitionSession", em);
    assertNotNull(ksession);
    try {
        // This needs to happen in the same transaction in order to be consistent
        ut.begin();
        //complete the pending work item handler
        ksession.getWorkItemManager().completeWorkItem(businessEntityByWorkItemId.getWorkItemId(), null);
        //mark the BusinessEntity as completed
        markBusinessEntityAsCompleted(businessEntityByWorkItemId.getId(), em);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling back because of: " + e.getMessage());
        ut.rollback();
    }
    //Dispose the session since we are no longer interested in it.
    ksession.dispose();
    //The only pending workItem related to the processId 2 should be 2
    //We can create queries to find out the pending workItems for a process 
    //instance or to find a process instance related to a business scenario 
    //using this approach.
    List<BusinessEntity> businessEntitiesProcessId = getBusinessEntitiesProcessId(2L, em);
    assertEquals(1, businessEntitiesProcessId.size());
    assertEquals(2, businessEntitiesProcessId.get(0).getWorkItemId());
    assertEquals(2, businessEntitiesProcessId.get(0).getProcessId());
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) BusinessEntity(com.salaboy.sessions.patterns.BusinessEntity) Person(com.salaboy.model.Person) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Example 34 with InitialContext

use of javax.naming.InitialContext in project jBPM5-Developer-Guide by Salaboy.

the class SingleSessionPatternsTest method singleSessionPerProcessInstance.

/**
     * This test starts 2 process instances of the same process definition
     * in independent sessions.
     * @throws Exception 
     */
@Test
public void singleSessionPerProcessInstance() throws Exception {
    //Creates an entity manager and get the user transaction. We are going
    //to need them later to interact with the business entities persisted
    //by the work item handlers we have configured in our session.
    EntityManager em = getEmf().createEntityManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    //Initial parameters for process instance #1
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params1 = new HashMap<String, Object>();
    params1.put("person", person);
    //Creates the ksession for process instance #1
    StatefulKnowledgeSession ksession1 = createProcessKnowledgeSession(person.getId());
    registerWorkItemHandlers(ksession1, person.getId(), em);
    int ksession1Id = ksession1.getId();
    //Starts process instance #1
    ksession1.startProcess("com.salaboy.process.AsyncInteractions", params1);
    //We don't want to use the ksession anymore so we will dispose it.
    //At this point MockAsyncExternalServiceWorkItemHandler has persisted
    //a business key that we can use later to retireve the session from
    //the database and continue with the execution of the process.
    ksession1.dispose();
    //Initial parameters for process instance #2
    Person person2 = new Person("Salaboy2", 29);
    Map<String, Object> params2 = new HashMap<String, Object>();
    params2.put("person", person2);
    //Creates a new ksession for process instance #2
    StatefulKnowledgeSession ksession2 = createProcessKnowledgeSession(person2.getId());
    registerWorkItemHandlers(ksession2, person2.getId(), em);
    int ksession2Id = ksession2.getId();
    //Starts process instance #2
    ksession2.startProcess("com.salaboy.process.AsyncInteractions", params2);
    //Dispose ksession2 as we don't want to use it anymore. Just like with
    //process instance #1, the work item handler associated to the task nodes
    //of the process has persisted a business key that we can use to continue
    //with the execution of this session later.
    ksession2.dispose();
    //Let's find the BusinessEntity persisted by process instance #2.
    //The key of the BusinessEntity is the the persnon's id.
    BusinessEntity businessEntity = getBusinessEntity(person2.getId(), em);
    assertNotNull(businessEntity);
    //the BusinessEntity must be of session #2
    assertEquals(businessEntity.getSessionId(), ksession2Id);
    //We shouldn't have more active business entities in the database.
    List<BusinessEntity> activeBusinessEntities = getActiveBusinessEntities(em);
    assertTrue(activeBusinessEntities.size() == 2);
    //Let' restore the session #2 using the information present in the BusinessEntity
    //Since we keep one kbase per ksession we also need to get it using
    //the information present in the BusinessEntity.
    ksession2 = loadKnowldgeSession(businessEntity.getSessionId(), businessEntity.getBusinessKey(), em);
    registerWorkItemHandlers(ksession2, businessEntity.getBusinessKey(), em);
    assertNotNull(ksession2);
    try {
        ut.begin();
        //Now that we have session #2 back we can complete the pending work item 
        //handler with the information present in BusinessEntity we can 
        ksession2.getWorkItemManager().completeWorkItem(businessEntity.getWorkItemId(), null);
        //The BusinessEntity is no longer needed so we can marked as completed
        //in the database.
        markBusinessEntityAsCompleted(businessEntity.getId(), em);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling back because of: " + e.getMessage());
        ut.rollback();
    }
    //We are done with ksession #2
    ksession2.dispose();
    //Now we are going to complete the pending work item handler of 
    //the process instance #1, but first we need to restore the session from
    //the database.
    businessEntity = getBusinessEntity(person.getId(), em);
    assertNotNull(businessEntity);
    //the BusinessEntity must be of session #1
    assertEquals(businessEntity.getSessionId(), ksession1Id);
    //load the ksession using the information present in BusinessEntity
    ksession1 = loadKnowldgeSession(businessEntity.getSessionId(), businessEntity.getBusinessKey(), em);
    assertNotNull(ksession1);
    try {
        // This needs to happen in the same transaction in order to be consistent
        ut.begin();
        //complete the pending work item handler
        ksession1.getWorkItemManager().completeWorkItem(businessEntity.getWorkItemId(), null);
        //mark the BusinessEntity as completed
        markBusinessEntityAsCompleted(businessEntity.getId(), em);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling back because of: " + e.getMessage());
        ut.rollback();
    }
    //dispose ksession #1
    ksession1.dispose();
    //We should have two active business entities in the database. Because the processes have two workitems each.
    activeBusinessEntities = getActiveBusinessEntities(em);
    assertEquals(2, activeBusinessEntities.size());
    //We should have two inactive business entities in the database.
    List<BusinessEntity> inActiveBusinessEntities = getInactiveBusinessEntities(em);
    assertEquals(2, inActiveBusinessEntities.size());
}
Also used : UserTransaction(javax.transaction.UserTransaction) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) BusinessEntity(com.salaboy.sessions.patterns.BusinessEntity) InitialContext(javax.naming.InitialContext) EntityManager(javax.persistence.EntityManager) Person(com.salaboy.model.Person) Test(org.junit.Test)

Example 35 with InitialContext

use of javax.naming.InitialContext in project jBPM5-Developer-Guide by Salaboy.

the class MultiSessionsPatternsTest method multiSessionsCollaboration.

/*
     * This test shows how a master session can automatically complete a work 
     * item handler in a slave session when the required information is present. 
     */
@Test
public void multiSessionsCollaboration() throws Exception {
    //Creates an entity manager and get the user transaction. We are going
    //to need them later to interact with the business entities persisted
    //by the work item handlers we have configured in our session.
    EntityManager em = getEmf().createEntityManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    //Creates and persists a new BusinessEntity containing the information
    //required by this test.
    StatefulKnowledgeSession interactionSession = null;
    BusinessEntity interactionSessionEntity = null;
    try {
        // This needs to happen in the same transaction if I want to keep it consistent
        ut.begin();
        //Creates a new session.
        interactionSession = createProcessInteractionKnowledgeSession("InteractionSession", em);
        //persists the required business entity.
        interactionSessionEntity = new BusinessEntity(interactionSession.getId(), 0, 0, "InteractionSession");
        // I need to join the Drools/jBPM transaction 
        em.joinTransaction();
        em.persist(interactionSessionEntity);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling Back because of: " + e.getMessage());
        ut.rollback();
        fail(e.getMessage());
    }
    assertNotNull(interactionSessionEntity);
    assertNotNull(interactionSessionEntity.getId());
    //Dispose the session.
    interactionSession.dispose();
    //Initial parameters for process instance #1
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    //Creates the ksession for process instance #1
    StatefulKnowledgeSession ksession = createProcessOneKnowledgeSession(person.getId());
    registerWorkItemHandlers(ksession, person.getId(), em);
    //Starts process instance #1
    ksession.startProcess("com.salaboy.process.AsyncInteractions", params);
    //Disposes the session.
    ksession.dispose();
    // The interaction Session has the responsability of mapping the WorkItems Ids with their corresponding
    // Business Interactions. This can be done with a Map/Registry or with a Knowledge Session to 
    // describe more complex patterns
    BusinessEntity sessionInteractionKey = getBusinessEntity("InteractionSession", em);
    interactionSession = loadKnowldgeSession(sessionInteractionKey.getSessionId(), "InteractionSession", em);
    interactionSession.setGlobal("em", em);
    interactionSession.setGlobal("ksessionSupport", this);
    // Look for all the pending Business Keys which represent an interaction and insert them into the interaction session
    List<BusinessEntity> pendingBusinessEntities = getActiveBusinessEntities(em);
    for (BusinessEntity be : pendingBusinessEntities) {
        if (!be.getBusinessKey().equals("InteractionSession")) {
            interactionSession.insert(be);
        }
    }
    // As soon as we add Data the completion will be triggered and the process will continue
    interactionSession.insert(new Data());
    interactionSession.fireAllRules();
    ksession.dispose();
}
Also used : UserTransaction(javax.transaction.UserTransaction) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Data(com.salaboy.model.Data) BusinessEntity(com.salaboy.sessions.patterns.BusinessEntity) InitialContext(javax.naming.InitialContext) EntityManager(javax.persistence.EntityManager) Person(com.salaboy.model.Person) Test(org.junit.Test)

Aggregations

InitialContext (javax.naming.InitialContext)1068 Test (org.junit.Test)325 EJBException (javax.ejb.EJBException)228 Properties (java.util.Properties)213 Context (javax.naming.Context)194 RemoteException (java.rmi.RemoteException)173 TestFailureException (org.apache.openejb.test.TestFailureException)172 NamingException (javax.naming.NamingException)168 AssertionFailedError (junit.framework.AssertionFailedError)168 JMSException (javax.jms.JMSException)167 RemoveException (javax.ejb.RemoveException)66 CreateException (javax.ejb.CreateException)57 DataSource (javax.sql.DataSource)55 Hashtable (java.util.Hashtable)54 Assembler (org.apache.openejb.assembler.classic.Assembler)47 EjbJar (org.apache.openejb.jee.EjbJar)41 NameNotFoundException (javax.naming.NameNotFoundException)40 ConfigurationFactory (org.apache.openejb.config.ConfigurationFactory)38 Connection (java.sql.Connection)37 StatelessBean (org.apache.openejb.jee.StatelessBean)30