简体   繁体   中英

Issue with UserTransaction in Java SE

in order to try Declarative Transaction Management in Java SE without a Java EE container, I simply converted the Transactional Servlet example that comes with Glassfish to Java SE. Please see original Servlet and the modified Java SE code attached.

I am using:

  1. JDK 7
  2. weld-se-2.2.0.Alpha2.jar
  3. glassfish4\\glassfish\\modules\\javax.transaction-api.jar
  4. glassfish4\\glassfish\\modules\\javax.inject.jar
  5. glassfish4\\glassfish\\modules\\javax.interceptor-api.jar
  6. glassfish4\\glassfish\\modules\\weld-osgi-bundle.jar
  7. Blank beans.xml file is present in the META-INF folder.
  8. I run the program from command line using a batch file with command "org.jboss.weld.environment.se.StartMain".

Issues:

  1. When I use @Inject to inject the UserTransaction, I get the following error:

    Exception in thread "main" org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type UserTransaction with qualifiers @Default at injection point [BackedAnnotatedField] @Inject TestSE.userTransaction at TestSE.userTransaction(TestSE.java:0)

    Hence, I replaced @Inject with @Resource.

  2. When using @Resource, the program runs OK, but it is not showing the correct Transaction behaviour. Even though the Bean Type is Mandatory, the Bean is injected and works fine and the subsequent userTransaction.begin() throws a Null Pointer Exception. All the 6 transaction attributes seem to have a strange behaviour.

There is definitely something wrong in the way, I am trying to execute it.Can someone please help me correct the issue.

Thanks you very much for the help.

BeanBase.java

public class BeanBase {
  public String getId() {
    return "ObjectId for this bean is " + this + "";
  }
  public String getId(String s) {
    return "ObjectId for this bean is " + this + " and "+ s;
  }
}

BeanMandatory.java

import javax.transaction.Transactional;

@Transactional(value = Transactional.TxType.MANDATORY)
public class BeanMandatory extends BeanBase {

}      

BeanSupports.java

import javax.transaction.Transactional;

@Transactional(value = Transactional.TxType.SUPPORTS)
public class BeanSupports extends BeanBase {
}

BeanRequiresNew.java

import javax.transaction.Transactional;

@Transactional(value = Transactional.TxType.REQUIRES_NEW)
public class BeanRequiresNew extends BeanBase {
}

BeanRequired.java

import javax.transaction.Transactional;

@Transactional(value = Transactional.TxType.REQUIRED)
public class BeanRequired extends BeanBase {
}

BeanNotSupported.java

import javax.transaction.Transactional;

@Transactional(value = Transactional.TxType.NOT_SUPPORTED)
public class BeanNotSupported extends BeanBase {
}

BeanNever.java

import javax.transaction.Transactional;

@Transactional(value = Transactional.TxType.NEVER)
public class BeanNever extends BeanBase {
}

Original Transactional Servlet code:

package transactional;

import javax.interceptor.InvocationContext;
import javax.inject.Inject;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.transaction.*;
import java.io.IOException;


@WebServlet(name="TransactionalServlet", urlPatterns={"/TransactionalServlet"})
public class TransactionalServlet extends HttpServlet {

    public static ServletOutputStream m_out;

    @Inject
    UserTransaction userTransaction;

    @Injecthytggt
    BeanMandatory beanMandatory;

    @Inject
    BeanNever beanNever;

    @Inject
    BeanNotSupported beanNotSupported;

    @Inject
    BeanRequired beanRequired;

    @Inject
    BeanRequiresNew beanRequiresNew;

    @Inject
    BeanSupports beanSupports;


    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String transactionalInterceptor = request.getParameter("TransactionalInterceptor");

        m_out = response.getOutputStream();
        m_out.println("<HTML>");
        m_out.println("<HEAD>");
        m_out.println("<title>CDI Sample Application for TransactionScoped Annotation</title>");
        m_out.println("</HEAD>");
        m_out.println("<BODY>");
        m_out.println("TransactionalInterceptor value is -> " + transactionalInterceptor);
        m_out.println("<BR><BR>");

        if (transactionalInterceptor.equalsIgnoreCase("MANDATORY")) {
            try {
                m_out.println("<b>Scenario: Invoking outside transaction. Should get an error.</b>");
                m_out.println("<BR><BR>");
                m_out.println(beanMandatory.getId());
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println("<BR><BR>");
            } catch (Exception transactionalException) {
                if (transactionalException.getCause() instanceof TransactionRequiredException) {
                    m_out.println("Got TransactionRequiredException for transactionalException.getCause() as expected.");
                    m_out.println("<BR><BR>");
                } else {
                    m_out.println("If you see this, it means there is something wrong!");
                    m_out.println(transactionalException.getMessage());
                    m_out.println("<BR><BR>");
                }
            }
            try {
                userTransaction.begin();
                m_out.println("<b>Scenario: Invoking within a transaction.</b>");
                m_out.println("<BR><BR>");
                m_out.println(beanMandatory.getId());
                m_out.println("<BR><BR>");
                userTransaction.commit();               
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            }
        } else if (transactionalInterceptor.equalsIgnoreCase("NEVER")) {
            try {
                m_out.println("<b>Scenario: Invoking outside transaction.</b>"); 
                m_out.println("<BR><BR>");
                m_out.println(beanNever.getId());
                m_out.println("<BR><BR>");
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            }
            try {
                userTransaction.begin();
                m_out.println("<b>Scenario: Invoking within a transaction. Should get an error.</b>");
                m_out.println("<BR><BR>");
                m_out.println(beanNever.getId());
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println("<BR><BR>");
            } catch (Exception transactionalException) {                    
                if (transactionalException.getCause() instanceof InvalidTransactionException) {
                    m_out.println("Got InvalidTransactionException for transactionalException.getCause() as expected.");
                    m_out.println("<BR><BR>");
                } else {
                    m_out.println("If you see this, it means there is something wrong!");
                    m_out.println(transactionalException.getMessage());
                    m_out.println("<BR><BR>");
                }
            } finally {
                try {
                    userTransaction.rollback();
                } catch (Exception e) {
                    m_out.println("Got unexpected exception in finally rollback for NEVER" + e.getMessage());
                }
            }
        } else if (transactionalInterceptor.equalsIgnoreCase("NOT_SUPPORTED")) {
            try {
                m_out.println("<b>Scenario: Invoking outside transaction.</b>"); 
                m_out.println("<BR><BR>");
                m_out.println(beanNotSupported.getId());
                m_out.println("<BR><BR>");
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            } 
            try {
                userTransaction.begin();
                m_out.println("<b>Scenario: Invoking within a transaction. Transaction is suspended during the method call. </b>");
                m_out.println("<BR><BR>");
                m_out.println(beanNotSupported.getId());
                userTransaction.commit();
                m_out.println("<BR><BR>");
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            }
        } else if (transactionalInterceptor.equalsIgnoreCase("REQUIRED")) {
            try {
                m_out.println("<b>Scenario: Invoking outside transaction. Transaction would be started automatically for the method call.</b>"); 
                m_out.println("<BR><BR>");
                m_out.println(beanRequired.getId());
                m_out.println("<BR><BR>");
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            } 
            try {
                userTransaction.begin();
                m_out.println("<b>Scenario: Invoking within a transaction.</b>");
                m_out.println("<BR><BR>");
                m_out.println(beanRequired.getId());
                m_out.println("<BR><BR>");
                userTransaction.commit();
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            }
        } else  if (transactionalInterceptor.equalsIgnoreCase("REQUIRES_NEW")) {
            try {
                m_out.println("<b>Scenario: Invoking outside transaction. Transaction would be started automatically for the method call.</b>");
                m_out.println("<BR><BR>");
                m_out.println(beanRequiresNew.getId());
                m_out.println("<BR><BR>");
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            } 
            try {
                userTransaction.begin();
                m_out.println("<b>Scenario: Invoking within a transaction. NEW Transaction would be started automatically for the method call. </b>");
                m_out.println("<BR><BR>");
                m_out.println(beanRequiresNew.getId());
                m_out.println("<BR><BR>");
                userTransaction.commit();
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            }
        } else  if (transactionalInterceptor.equalsIgnoreCase("SUPPORTS")) {
            try {
                m_out.println("<b>Scenario: Invoking outside transaction. Method is executed outside transaction. </b>");
                m_out.println("<BR><BR>");
                m_out.println(beanSupports.getId());
                m_out.println("<BR><BR>");
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            } 
            try {
                userTransaction.begin();
                m_out.println("<b>Scenario: Invoking within a transaction. Method is executed within transaction context.</b>");
                m_out.println("<BR><BR>");
                m_out.println(beanSupports.getId());
                m_out.println("<BR><BR>");
                userTransaction.commit();
            } catch (Exception e){
                m_out.println("If you see this, it means there is something wrong!");
                m_out.println(e.getMessage());
                m_out.println("<BR><BR>");
            }
        } 

        m_out.println("</BODY>");
        m_out.println("</HTML>");
    }

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }


}

My Java SE example TestSE.java:

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.transaction.UserTransaction;
import javax.transaction.*;
import javax.enterprise.event.Observes;

import org.jboss.weld.environment.se.events.ContainerInitialized;

public class TestSE {
    //@Inject //since this was throwing an exception, I used @Resource 
    @Resource
    UserTransaction userTransaction;

    @Inject
    BeanMandatory beanMandatory;

    @Inject
    BeanNever beanNever;

    @Inject
    BeanNotSupported beanNotSupported;

    @Inject
    BeanRequired beanRequired;

    @Inject
    BeanRequiresNew beanRequiresNew;

    @Inject
    BeanSupports beanSupports;

    public void process(@Observes ContainerInitialized init)
    {
        // TODO Auto-generated method stub
        String command = null;
        BufferedReader br = null;
        boolean loop = true;

        try
        {
            while(loop)
            {
                System.out.println("> 1 - Mandatory, 2 - Never, 3 - Not Supported, 4 - Required, 5 - Requires New, 6 - Supports, q - Quit");
                System.out.println("Enter your choice and hit enter:");
                br = new BufferedReader(new InputStreamReader(System.in));
                command = br.readLine();
                System.out.println("Received command[" + command + "]");

                switch(command)
                {
                    case "1":
                        System.out.println("Processing Mandatory");

                        try 
                        {
                            System.out.println("Scenario: Invoking outside transaction. Should get an error.");
                            System.out.println(beanMandatory.getId());
                            System.out.println("If you see this, it means there is something wrong!");
                        }
                        catch (Exception transactionalException) 
                        {
                            if (transactionalException.getCause() instanceof TransactionRequiredException) 
                            {
                                System.out.println("Got TransactionRequiredException for transactionalException.getCause() as expected.");
                            }
                            else 
                            {
                                System.out.println("2 If you see this, it means there is something wrong!");
                                System.out.println(transactionalException.getMessage());
                            }
                        }

                        try 
                        {
                            userTransaction.begin();
                            System.out.println("Scenario: Invoking within a transaction.");
                            System.out.println(beanMandatory.getId());
                            userTransaction.commit();               
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        break;
                    case "2":
                        System.out.println("Processing Never");

                        try 
                        {
                            System.out.println("Scenario: Invoking outside transaction."); 
                            System.out.println(beanNever.getId());
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        try 
                        {
                            userTransaction.begin();
                            System.out.println("Scenario: Invoking within a transaction. Should get an error.");
                            System.out.println(beanNever.getId());
                            System.out.println("If you see this, it means there is something wrong!");
                        }
                        catch (Exception transactionalException) 
                        {                   
                            if (transactionalException.getCause() instanceof InvalidTransactionException) 
                            {
                                System.out.println("Got InvalidTransactionException for transactionalException.getCause() as expected.");
                            }
                            else 
                            {
                                System.out.println("If you see this, it means there is something wrong!");
                                System.out.println(transactionalException.getMessage());
                            }
                        }
                        finally 
                        {
                            try 
                            {
                                userTransaction.rollback();
                            }
                            catch (Exception e) 
                            {
                                System.out.println("Got unexpected exception in finally rollback for NEVER" + e.getMessage());
                            }
                        }   

                        break;
                    case "3":
                        System.out.println("Processing NotSupported");

                        try 
                        {
                            System.out.println("Scenario: Invoking outside transaction."); 
                            System.out.println(beanNotSupported.getId());
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        try 
                        {
                            userTransaction.begin();
                            System.out.println("Scenario: Invoking within a transaction. Transaction is suspended during the method call. ");
                            System.out.println(beanNotSupported.getId());
                            userTransaction.commit();
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        break;
                    case "4":
                        System.out.println("Processing Required");

                        try 
                        {
                            System.out.println("Scenario: Invoking outside transaction. Transaction would be started automatically for the method call."); 
                            System.out.println(beanRequired.getId());
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        try 
                        {
                            userTransaction.begin();
                            System.out.println("Scenario: Invoking within a transaction.");
                            System.out.println(beanRequired.getId());
                            userTransaction.commit();
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        break;
                    case "5":
                        System.out.println("Processing RequiresNew");

                        try
                        {
                            System.out.println("Scenario: Invoking outside transaction. Transaction would be started automatically for the method call.");
                            System.out.println(beanRequiresNew.getId());
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        try 
                        {
                            userTransaction.begin();
                            System.out.println("Scenario: Invoking within a transaction. NEW Transaction would be started automatically for the method call. ");
                            System.out.println(beanRequiresNew.getId());
                            userTransaction.commit();
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        break;
                    case "6":
                        System.out.println("Processing Supports");

                        try 
                        {
                            System.out.println("Scenario: Invoking outside transaction. Method is executed outside transaction. ");
                            System.out.println(beanSupports.getId());
                        }
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }

                        try 
                        {
                            userTransaction.begin();
                            System.out.println("Scenario: Invoking within a transaction. Method is executed within transaction context.");
                            System.out.println(beanSupports.getId());
                            userTransaction.commit();
                        } 
                        catch (Exception e)
                        {
                            System.out.println("If you see this, it means there is something wrong!");
                            System.out.println(e.getMessage());
                        }                       
                        break;
                    case "q":
                        System.out.println("Quitting...");
                        loop = false;
                }// eof switch
            }// eof for
        }
        catch(Exception excp)
        {
            System.out.println("An exception has occured.");
            excp.printStackTrace();
        }
    }// eof process

}//eof class

Please see this link https://github.com/luiz158/usertransaction-in-java-se

I read your issue and make this test.

see you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM