[ 
https://issues.apache.org/jira/browse/OPENEJB-1968?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13531442#comment-13531442
 ] 

Howard W. Smith, Jr. commented on OPENEJB-1968:
-----------------------------------------------

Per David Blevins, I am pasting an 'earlier' (more of an 'original') version of 
the EmailStatelessBean, which was dated around the Dec 11, 2012 11:59pm. Please 
NOTE, the implementation has changed since this version. I no longer have much 
code in this bean any longer.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils.mail;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Date;
import java.util.List;
import javax.ejb.EJBException;

import javax.ejb.Schedule;
import javax.ejb.Stateless;

import javax.inject.Inject;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import jpa.entities.Address;
import jpa.entities.AddressLine;
import jpa.entities.AddressType;
import jpa.entities.AuditTrail;

import jpa.entities.Customer;
import jpa.entities.Destination;
import jpa.entities.EmailAddress;
import jpa.entities.EmailAddressType;
import jpa.entities.Flight;
import jpa.entities.OrderCostDetails;
import jpa.entities.OrderCustomerLeader;
import jpa.entities.OrderCustomerPointOfContact;
import jpa.entities.OrderDetails;
import jpa.entities.OrderNotes;
import jpa.entities.Orders;
import jpa.entities.Origin;
import jpa.entities.Phone;
import jpa.entities.PhoneType;
import jpa.entities.PointOfContact;
import jpa.entities.Users;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import pf.ApplicationScopeBean;


/**
 *
 * @author Administrator
 * 
 * Using EJB Timer Service
 * http://stackoverflow.com/questions/8482764/using-ejb-timer-service
 * Automatic EJB Timer on Glassfish Server not triggering
 * 
http://stackoverflow.com/questions/13092567/automatic-ejb-timer-on-glassfish-server-not-triggering
 * Using the Timer Service (Java EE 6 Tutorial)
 * http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html
 */
@Stateless
public class EmailStatelessBean {
    
    private Boolean debug = false;
    
    @Inject
    private ApplicationScopeBean applicationScopeBean;
    
    @PersistenceContext
    private EntityManager em;
    
    private EmailHandler emailHandler = null;
    
    @Schedule(hour="*", minute="*/10", second="0", persistent=false)
    public void getEmails() {
        
        if (debug) {
            applicationScopeBean.log("EmailStatelessBean.getEmails(): invoked " 
+ new Date());
        }
        
        Boolean usersAreLoggedIn = applicationScopeBean.usersAreLoggedIn();
        if (debug) {
            applicationScopeBean.log("EmailStatelessBean.getEmails(): 
usersAreLoggedIn = " + usersAreLoggedIn);
        }
        
        // to prevent users from logging in during request to email server
        if (!usersAreLoggedIn) {
            applicationScopeBean.setProcessingAirportShuttleRequests(true);
        }
        
        if (applicationScopeBean.getAirportShuttleRequestsPending() && 
usersAreLoggedIn) {
            
applicationScopeBean.sendAirportShuttleRequestsPendingNotification();
            if (debug) {
                String msg = "exited, since Airport Shuttle requests pending 
AND users are logged in";
                applicationScopeBean.log("EmailStatelessBean.getEmails(): " + 
msg);
            }
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            return;
        }
        
        emailHandler = new EmailHandler();
        try {
            emailHandler.initialize();
        } catch (Exception e) {
            String msg = "Error initializing GMAIL IMAP session.";
            applicationScopeBean.log("EmailStatelessBean.getEmails(): " + msg);
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            return;
        }
        
        try {
            emailHandler.loadEmailsFromInbox();
        } catch (Exception e) {
            String msg = "Error loading emails from Inbox";
            applicationScopeBean.log("EmailStatelessBean.getEmails(): " + msg);
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            return;
        }
        
        // if users were able to login during request to email server
        if (!usersAreLoggedIn && applicationScopeBean.usersAreLoggedIn()) {
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            usersAreLoggedIn = true;
        }
        
        Gson gson;
        try {
            gson = new 
GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
        } catch (Exception e) {
            String msg = "Error initializing Gson";
            applicationScopeBean.log("EmailStatelessBean.getEmails(): " + msg);
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            return;
        }
        
        if (emailHandler == null || emailHandler.getEmails() == null || 
emailHandler.getEmails().isEmpty()) {
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            return;
        }

        if (debug) {
            applicationScopeBean.log("EmailStatelessBean.getEmails(): # of 
emails retrieved = " +
                                     emailHandler.getEmails().size());
        }

        Boolean deleteSelectedEmails = false;
        List<Email> emails = emailHandler.getEmails();

        // if users were able to login during request to email server
        if (!usersAreLoggedIn && applicationScopeBean.usersAreLoggedIn()) {
            applicationScopeBean.setProcessingAirportShuttleRequests(false);
            usersAreLoggedIn = true;
        }
        
        for (int i = 0; i < emails.size(); i++) {
            Email email = emails.get(i);
            StringBuilder msg = new StringBuilder(200);
            if (debug) {
                msg.append("FROM: " + email.getFrom());
                msg.append("; TO: " + email.getRecipients());
                msg.append("; SUBJECT: " + email.getSubject());
            }
            /*
             * *** ELSE DELETE ALL OTHER EMAILS!!! ***
             */
            if (email.getSubject().contains("Results from Airport Shuttle")) {
                applicationScopeBean.setAirportShuttleRequestsPending(true);
                if (usersAreLoggedIn) {
                    
applicationScopeBean.sendAirportShuttleRequestsPendingNotification();
                    if (debug) {
                        String debugMsg = "exited, since Airport Shuttle 
requests pending AND users are logged in";
                        
applicationScopeBean.log("EmailStatelessBean.getEmails(): " + debugMsg);
                    }
                    
applicationScopeBean.setProcessingAirportShuttleRequests(false);
                    return;
                }
                
                applicationScopeBean.setProcessingAirportShuttleRequests(true);
                
                if (debug) {
                    msg.append("\n").append(email.body);
                }

                jsonAirportShuttleResults results = null;
                try {
                    results = gson.fromJson(email.body, 
jsonAirportShuttleResults.class);
                    if (debug) {
                        msg.append("\n\nBelow is JSON data that was 
imported:\n\n")
                           .append(gson.toJson(results));
                    }
                } catch (Exception e) {
                    System.out.println("EmailStatelessBean.getEmails(): gson 
exception:");
                    e.printStackTrace();
                }
                if (debug) {
                    applicationScopeBean.log("EmailStatelessBean.getEmails(): " 
+ msg.toString());
                }
                if (processAirportShuttleRequest(results)) {
                    deleteSelectedEmails = true;
                    email.setSelected(true);
                    emails.set(i, email);
                    if (debug) {
                        
applicationScopeBean.log("EmailStatelessBean.getEmails(): 
processAirportShuttleRequest returned TRUE, SELECT email for deletion");
                    }
                }
            }
            else {
                // delete any other emails that are in the inbox
                deleteSelectedEmails = true;
                email.setSelected(true);
                emails.set(i, email);
            }
        }
        if (deleteSelectedEmails) {
            emailHandler.setEmails(emails);
            try {
                if (debug) {
                    applicationScopeBean.log("EmailStatelessBean.getEmails(): 
BEFORE emailHandler.deleteSelectedEmails() " + new Date());
                }
                emailHandler.deleteSelectedEmails();
                if (debug) {
                    applicationScopeBean.log("EmailStatelessBean.getEmails(): 
AFTER emailHandler.deleteSelectedEmails() " + new Date());
                }
            } catch (Exception e) {
                applicationScopeBean.log("EmailStatelessBean.getEmails(): 
exception while deleting emails");
                e.printStackTrace();
            }
        }
        
        try {
            emailHandler.closeFolderAndStore();
        } catch (Exception e) {
            String msg = "Error closing folder and store";
            applicationScopeBean.log("EmailStatelessBean.getEmails(): " + msg);
        }
        
        // end of process; update applicationScopeBean, accordingly
        applicationScopeBean.setAirportShuttleRequestsPending(false);
        applicationScopeBean.setProcessingAirportShuttleRequests(false);
    }
    
    private Boolean createDestination(Destination destinationToAdd, String 
destination,
                                      String address, String city, String 
state, String zip) {
        destinationToAdd.setDestinationTx(destination);

        Boolean addressPersisted = false;
        Address a = null;
        if (address.length() > 0 || city.length() > 0 || state.length() > 0 || 
zip.length() > 0) {
            a = new Address(1);
            a.setAddressTypeId(getAddressTypeByName("Business"));
            a.setCity(city);
            a.setState(state);
            a.setPostalCode(zip);
            try {
                // update database
                em.persist(a);
                em.flush();
                addressPersisted = true;
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createDestination(): exception 
persisting DESTINATION ADDRESS");
                e.printStackTrace();
            }

            if (addressPersisted && address.length() > 0) {
                AddressLine addressLine_1 = new AddressLine(1);
                addressLine_1.setAddressLineTx(address);
                try {
                    // update database
                    em.persist(addressLine_1);
                    em.flush();
                    a.addAddressLine(addressLine_1);
                    addressLine_1.addAddress(a);
                } catch (Exception e) {
                    
applicationScopeBean.log("EmailStatelessBean.createDestination(): exception 
persisting DESTINATION ADDRESS LINE");
                    e.printStackTrace();
                }
            }
        }

        try {
            // update database
            em.persist(destinationToAdd);
            em.flush();
            if (addressPersisted) {
                destinationToAdd.addAddress(a);
                a.addDestination(destinationToAdd);
            }
        } catch (Exception e) {
            
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting DESTINATION ADDRESS LINE");
            e.printStackTrace();
            return false;
        }
        
        return true;
    }
    
    private Boolean createOrderForAirportShuttle(jsonAirportShuttleResults 
request,
                                                 jsonAirportShuttleResults
                                                
.jsonAirportShuttleFlightDetails flightDetails) {
        
        StringBuilder details = new StringBuilder(200),
                      notes = new StringBuilder(200);
        
        OrderDetails orderDetails = new OrderDetails(1);
        orderDetails.setDetailsTx("");
        details.append(request.getMessage());
        
        OrderNotes orderNotes = new OrderNotes(1);
        orderNotes.setNotesTx("");
        
        Orders order = new Orders(1);
        setDefaultValues(order);
        order.setIntrastate('Y');
        
        DateTimeFormatter formatter;
        
        formatter = DateTimeFormat.forPattern("MM/dd/yyyy hh:mm a");
        String dtString = flightDetails.getFlightDate() + " " +
                          flightDetails.getFlightTime().toLowerCase();
        DateTime flightDateTime = DateTime.parse(dtString, formatter);
        
        order.setTripDateTime(flightDateTime.minusHours(1).toDate());
        
order.setReportDateTime(flightDateTime.minusHours(1).minusMinutes(15).toDate());
        order.setReturnDateTime(order.getTripDateTime());
        notes.append("Please contact customer and confirm REPORT time.");
        
        try {
            
order.setPassengers(Short.valueOf(flightDetails.getNbrOfPassengers()));
        } catch (Exception e) {
            if (details.length() > 0) {
                details.append("\n");
            }
            details.append("Nbr of passengers: " + 
flightDetails.getNbrOfPassengers());
        }

        // set created and changed date fields
        order.setCreatedDt(new Date());

        try {
            // update database
            em.persist(order);
            em.flush();
        } catch (Exception e) {
            
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting new ORDER");
            e.printStackTrace();
            return false;
        }
        
        if (details.length() > 0) {
            orderDetails.setDetailsTx(details.toString());
            try {
                // update database
                em.persist(orderDetails);
                em.flush();
                order.setDetailsId(orderDetails);
                orderDetails.addOrder(order);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting new ORDER DETAILS");
                e.printStackTrace();
            }
        }

        // default customer = AIRPORT SHUTTLE
        Integer airportShuttleId = 1384;
        Customer customer = null;
        try {
            customer = getCustomerForCustomerId(airportShuttleId);
        } catch (Exception e) {
            
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception while getting customer, AIRPORT SHUTTLE (1384)");
            e.printStackTrace();
            try {
                customer = getCustomerForCustomerId(1000);
            } catch (Exception innerE) {
                
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception while getting customer, NO CUSTOMER (1000)");
                innerE.printStackTrace();
            }
        }
        if (customer == null) {
            
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
return, due to database issues");
            return false;
        }
        
        order.setCustomerId(customer);
        customer.addOrder(order);
        
        if (customer.getLeaderPointOfContactId() != null) {
            PointOfContact pointOfContact = 
customer.getLeaderPointOfContactId();
            OrderCustomerLeader orderCustomerLeader =
                    new OrderCustomerLeader(order.getOrderId(), 
customer.getCustomerId(),
                                            
pointOfContact.getPointOfContactId());
            try {
                // update database
                em.persist(orderCustomerLeader);
                em.flush();
                order.addOrderCustomerLeader(orderCustomerLeader);
                customer.addOrderCustomerLeader(orderCustomerLeader);
                pointOfContact.addOrderCustomerLeader(orderCustomerLeader);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting new ORDER CUSTOMER LEADER");
                e.printStackTrace();
            }
        }
        
        // ORDERED BY point of contact
        PointOfContact orderedByPOC = new PointOfContact(1);
        if (createPointOfContact(orderedByPOC, request.getName(), 
request.getAddress(), request.getCity(),
                                 request.getState(), request.getZip(), 
request.getEmail(),
                                 request.getHomeBusPhone(), 
request.getMobilePhone())) {
            
            OrderCustomerPointOfContact orderCustPOC;
            orderCustPOC = new OrderCustomerPointOfContact(order.getOrderId(), 
customer.getCustomerId(),
                                                           
orderedByPOC.getPointOfContactId());
            try {
                // update database
                em.persist(orderCustPOC);
                em.flush();
                order.addOrderCustomerPointOfContact(orderCustPOC);
                customer.addOrderCustomerPointOfContact(orderCustPOC);
                orderedByPOC.addOrderCustomerPointOfContact(orderCustPOC);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting ORDERED BY POINT OF CONTACT");
                e.printStackTrace();
            }
        }

        // CONTACT PERSONS
        PointOfContact contactPerson = new PointOfContact(1);
        if (createPointOfContact(contactPerson, request.getName(), 
request.getAddress(), request.getCity(),
                                 request.getState(), request.getZip(), 
request.getEmail(),
                                 request.getHomeBusPhone(), 
request.getMobilePhone())) {
            
            contactPerson.addOrder(order);
            order.addPointOfContact(contactPerson);
        }
        
        String airportToAddToFlight, airportAddress, airportCity,
               airportState, airportZip, templateName;
        switch (flightDetails.getAirport()) {
            case "Newport News-Williamsburg International":
                airportToAddToFlight = "Newport News";
                airportAddress = "900 Bland Blvd";
                airportCity = "Newport News";
                airportState = "VA";
                airportZip = "23602";
                templateName = "AIRPORT SHUTTLE: Newport News";
                break;
            case "Norfolk International":
                airportToAddToFlight = "Norfolk";
                airportAddress = "2200 Norview Ave";
                airportCity = "Norfolk";
                airportState = "VA";
                airportZip = "23518";
                templateName = "AIRPORT SHUTTLE: Norfolk";
                break;
            case "Richmond International":
                airportToAddToFlight = "Richmond";
                airportAddress = "1 Richard E Byrd Terminal Drive";
                airportCity = "Richmond";
                airportState = "VA";
                airportZip = "23250";
                templateName = "AIRPORT SHUTTLE: Richmond";
                break;
            default:
                airportToAddToFlight = flightDetails.getAirportOther();
                airportAddress = "";
                airportCity = "";
                airportState = "";
                airportZip = "";
                templateName = null;
                break;
        }
        
        /*
         * Origin and destination
         * 1. If "Arrival", then origin = airport
         * 2. If "Departure", then destination = airport
         */
        Boolean originAdded = false, destinationAdded = false;
        Destination destinationToAdd = new Destination(1);
        Origin originToAdd = new Origin(1);
        String origin, destination;
        if (flightDetails.getArrivalOrDeparture().equals("Arrival")) {
            
            if (templateName != null) {
                templateName += " (FROM)";
            }
            
            if (flightDetails.getAirportOther().length() > 0) {
                origin = flightDetails.getAirportOther();
            }
            else {
                origin = flightDetails.getAirport();
            }
            originAdded = createOrigin(originToAdd, origin, airportAddress,
                                       airportCity, airportState, airportZip);
            destinationAdded = createDestination(destinationToAdd, 
flightDetails.getOriginDestinationName(),
                                                 
flightDetails.getOriginDestinationAddress(),
                                                 
flightDetails.getOriginDestinationCity(),
                                                 
flightDetails.getOriginDestinationState(),
                                                 
flightDetails.getOriginDestinationZip());
        }
        
        // if (flightDetails.getArrivalOrDeparture().equals("Departure"))
        else {
            
            if (templateName != null) {
                templateName += " (TO)";
            }
            
            if (flightDetails.getAirportOther().length() > 0) {
                destination = flightDetails.getAirportOther();
            }
            else {
                destination = flightDetails.getAirport();
            }
            destinationAdded = createDestination(destinationToAdd, destination, 
airportAddress,
                                                 airportCity, airportState, 
airportZip);
            originAdded = createOrigin(originToAdd, 
flightDetails.getOriginDestinationName(),
                                       
flightDetails.getOriginDestinationAddress(),
                                       flightDetails.getOriginDestinationCity(),
                                       
flightDetails.getOriginDestinationState(),
                                       flightDetails.getOriginDestinationZip());
        }
        
        if (destinationAdded) {
            destinationToAdd.addOrder(order);
            order.addDestination(destinationToAdd);
        }
        if (originAdded) {
            originToAdd.addOrder(order);
            order.addOrigin(originToAdd);
        }
        
        Flight flight = new Flight(1);
        flight.setAirportTx(airportToAddToFlight);
        flight.setAirlineTx(flightDetails.getAirline());
        flight.setFlightNumber(flightDetails.getFlightNbr());
        flight.setFlightType(flightDetails.getArrivalOrDeparture().charAt(0));
        flight.setFlightDateTime(flightDateTime.toDate());
        try {
            // update database
            em.persist(flight);
            em.flush();
            flight.addOrder(order);
            order.addFlight(flight);
        } catch (Exception e) {
            
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting new FLIGHT");
            e.printStackTrace();
        }
        
        Orders orderTemplate = getTemplate(templateName);
        if (orderTemplate != null) {
            try {
                List<OrderCostDetails> ocdList = 
getOrderCostDetailsForOrder(orderTemplate.getOrderId());
                if (ocdList != null && !ocdList.isEmpty()) {
                    for (OrderCostDetails ocd : ocdList) {
                        createOrderCostDetails(order, ocd);
                    }
                }
                order.setDiscount(orderTemplate.getDiscount());
                order.setDiscountRate(orderTemplate.getDiscountRate());
                order.setTotalCost(orderTemplate.getTotalCost());
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception while creating ORDER COST DETAILS");
                e.printStackTrace();
            }
        }
        
        if (notes.length() > 0) {
            orderNotes.setNotesTx(notes.toString());
            try {
                // update database
                em.persist(orderNotes);
                em.flush();
                order.setNotesId(orderNotes);
                orderNotes.addOrder(order);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting new ORDER NOTES");
                e.printStackTrace();
            }
        }
        
        // get administrator user for audit trail purposes
        Users user = getUserByName("administrator");

        AuditTrail auditTrail = new AuditTrail(1);
        auditTrail.setAuditTrailDt(new Date());
        auditTrail.setDescriptionTx("Added per Results from Airport Shuttle 
(www.oleta.com)");
        auditTrail.setUserName(user);
        try {
            // update database
            em.persist(auditTrail);
            em.flush();
            order.addAuditTrail(auditTrail);
            auditTrail.addOrder(order);
        } catch (Exception e) {
            
applicationScopeBean.log("EmailStatelessBean.createOrderForAirportShuttle(): 
exception persisting new ORDER AUDIT TRAIL");
            e.printStackTrace();
        }
        return true;
    }
    
    private void createOrderCostDetails(Orders order, OrderCostDetails ocd) {
        if (ocd.getServiceAbbr() == null && ocd.getNbrOfPassengers() == 0) {
            return;
        }

        Boolean yesNoFlags = true, charges = true, costValues = true,
                userModifiedValues = true, otherValues = true, 
checkForNullValues = false;

        try {
            OrderCostDetails orderCostDetails = new OrderCostDetails();
            initOrderCostDetails(orderCostDetails, yesNoFlags, charges, 
costValues,
                                 userModifiedValues, otherValues, 
checkForNullValues);

            
orderCostDetails.setApplyChargeFuelSurcharge(ocd.getApplyChargeFuelSurcharge());
            
orderCostDetails.setApplyChargeGratuity(ocd.getApplyChargeGratuity());
            orderCostDetails.setApplyChargeMeals(ocd.getApplyChargeMeals());
            
orderCostDetails.setApplyCurrentCharges(ocd.getApplyCurrentCharges());

            orderCostDetails.setChargeDeadMile(ocd.getChargeDeadMile());
            
orderCostDetails.setChargeEachAdditionalHour(ocd.getChargeEachAdditionalHour());
            orderCostDetails.setChargeFirstHours(ocd.getChargeFirstHours());
            orderCostDetails.setChargeFirstMiles(ocd.getChargeFirstMiles());
            orderCostDetails.setChargeFirstRate(ocd.getChargeFirstRate());
            
orderCostDetails.setChargeFuelSurcharge(ocd.getChargeFuelSurcharge());
            orderCostDetails.setChargeGratuity(ocd.getChargeGratuity());
            orderCostDetails.setChargeLayover(ocd.getChargeLayover());
            orderCostDetails.setChargeLiveMile(ocd.getChargeLiveMile());
            orderCostDetails.setChargeMeals(ocd.getChargeMeals());

            
orderCostDetails.setCostAdditionalDriver(ocd.getCostAdditionalDriver());
            orderCostDetails.setCostDays(ocd.getCostDays());
            orderCostDetails.setCostDeadMile(ocd.getCostDeadMile());
            orderCostDetails.setCostFuelSurcharge(ocd.getCostFuelSurcharge());
            orderCostDetails.setCostGratuity(ocd.getCostGratuity());
            orderCostDetails.setCostLayover(ocd.getCostLayover());
            orderCostDetails.setCostLiveMile(ocd.getCostLiveMile());
            orderCostDetails.setCostMeals(ocd.getCostMeals());
            orderCostDetails.setCostMiles(ocd.getCostMiles());
            orderCostDetails.setCostMilesOrDays(ocd.getCostMilesOrDays());
            orderCostDetails.setSubtotal(ocd.getSubtotal());

            
orderCostDetails.setChargeAdditionalDriverHours(ocd.getChargeAdditionalDriverHours());
            
orderCostDetails.setChargeAdditionalDriverMiles(ocd.getChargeAdditionalDriverMiles());
            orderCostDetails.setCostOther(ocd.getCostOther());
            orderCostDetails.setCostParking(ocd.getCostParking());
            orderCostDetails.setCostPermits(ocd.getCostPermits());
            orderCostDetails.setCostTolls(ocd.getCostTolls());
            orderCostDetails.setHoursPerDay(ocd.getHoursPerDay());
            
orderCostDetails.setNbrOfAdditionalDriverHours(ocd.getNbrOfAdditionalDriverHours());
            
orderCostDetails.setNbrOfAdditionalDriverMiles(ocd.getNbrOfAdditionalDriverMiles());
            
orderCostDetails.setNbrOfAdditionalDrivers(ocd.getNbrOfAdditionalDrivers());
            orderCostDetails.setNbrOfDays(ocd.getNbrOfDays());
            orderCostDetails.setNbrOfDeadMiles(ocd.getNbrOfDeadMiles());
            orderCostDetails.setNbrOfLayovers(ocd.getNbrOfLayovers());
            orderCostDetails.setNbrOfLiveMiles(ocd.getNbrOfLiveMiles());

            orderCostDetails.setNbrOfPassengers(ocd.getNbrOfPassengers());
            
orderCostDetails.setNbrOfVehicleOperators(ocd.getNbrOfVehicleOperators());
            orderCostDetails.setNbrOfVehicles(ocd.getNbrOfVehicles());
            orderCostDetails.setServiceAbbr(ocd.getServiceAbbr());

            orderCostDetails.setCostDetailsId(1);
            em.persist(orderCostDetails);
            em.flush();
            
            // add orderCostDetails to order
            orderCostDetails.addOrder(order);
            order.addOrderCostDetail(orderCostDetails);
            /*
             * the following should not be necessary
             * 
            em.merge(orderCostDetails);
            em.flush();
             */
        } catch (Exception e) {
            throw e;
        }
    }

    private Boolean createOrigin(Origin originToAdd, String origin,
                                      String address, String city, String 
state, String zip) {
        originToAdd.setOriginTx(origin);

        Boolean addressPersisted = false;
        Address a = null;
        if (address.length() > 0 || city.length() > 0 || state.length() > 0 || 
zip.length() > 0) {
            a = new Address(1);
            a.setAddressTypeId(getAddressTypeByName("Business"));
            a.setCity(city);
            a.setState(state);
            a.setPostalCode(zip);
            try {
                // update database
                em.persist(a);
                em.flush();
                addressPersisted = true;
            } catch (Exception e) {
                applicationScopeBean.log("EmailStatelessBean.createOrigin(): 
exception persisting ORIGIN ADDRESS");
                e.printStackTrace();
            }

            if (addressPersisted && address.length() > 0) {
                AddressLine addressLine_1 = new AddressLine(1);
                addressLine_1.setAddressLineTx(address);
                try {
                    // update database
                    em.persist(addressLine_1);
                    em.flush();
                    a.addAddressLine(addressLine_1);
                    addressLine_1.addAddress(a);
                } catch (Exception e) {
                    
applicationScopeBean.log("EmailStatelessBean.createOrigin(): exception 
persisting ORIGIN ADDRESS LINE");
                    e.printStackTrace();
                }
            }
        }

        try {
            // update database
            em.persist(originToAdd);
            em.flush();
            if (addressPersisted) {
                originToAdd.addAddress(a);
                a.addOrigin(originToAdd);
            }
        } catch (Exception e) {
            applicationScopeBean.log("EmailStatelessBean.createOrigin(): 
exception persisting ORIGIN ADDRESS LINE");
            e.printStackTrace();
            return false;
        }
        
        return true;
    }
    
    private Boolean createPointOfContact(PointOfContact pointOfContact, String 
name, String address,
                                         String city, String state, String zip, 
String email,
                                         String homeBusPhone, String 
mobilePhone) {
        
        pointOfContact.setPointOfContactName(name);
        pointOfContact.setCreatedDt(new Date());
        pointOfContact.setChangedDt(null);
        Boolean pointOfContactPersisted = false;
        try {
            // update database
            em.persist(pointOfContact);
            em.flush();
            pointOfContactPersisted = true;
        } catch (Exception e) {
            
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting POINT OF CONTACT");
            e.printStackTrace();
        }
        
        if (pointOfContactPersisted) {
            
            // add address
            Address a = new Address(1);
            a.setCity(city);
            a.setState(state);
            a.setPostalCode(zip);
            a.setAddressTypeId(getAddressTypeByName("Business"));
            Boolean addressPersisted = false;
            try {
                // update database
                em.persist(a);
                em.flush();
                pointOfContact.addAddress(a);
                a.addPointOfContact(pointOfContact);
                addressPersisted = true;
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting POINT OF CONTACT ADDRESS");
                e.printStackTrace();
            }
            
            if (addressPersisted) {
                AddressLine addressLine_1 = new AddressLine(1);
                addressLine_1.setAddressLineTx(address);
                try {
                    // update database
                    em.persist(addressLine_1);
                    em.flush();
                    a.addAddressLine(addressLine_1);
                    addressLine_1.addAddress(a);
                } catch (Exception e) {
                    
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting POINT OF CONTACT ADDRESS LINE");
                    e.printStackTrace();
                }
            }
            
            EmailAddress emailAddress1 = new EmailAddress(1);
            emailAddress1.setEmailAddressTx(email);
            
emailAddress1.setEmailAddressTypeId(getEmailAddressTypeByName("Business"));
            try {
                // update database
                em.persist(emailAddress1);
                em.flush();
                pointOfContact.addEmailAddress(emailAddress1);
                emailAddress1.addPointOfContact(pointOfContact);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting EMAIL ADDRESS # 1");
                e.printStackTrace();
            }
            
            Phone phone1 = new Phone(1);
            phone1.setPhoneNumber(homeBusPhone);
            phone1.setPhoneTypeId(getPhoneTypeByName("Business"));
            try {
                // update database
                em.persist(phone1);
                em.flush();
                pointOfContact.addPhone(phone1);
                phone1.addPointOfContact(pointOfContact);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting POINT OF CONTACT PHONE # 1");
                e.printStackTrace();
            }
            
            Phone phone2 = new Phone(1);
            phone2.setPhoneNumber(mobilePhone);
            phone2.setPhoneTypeId(getPhoneTypeByName("Mobile"));
            try {
                // update database
                em.persist(phone2);
                em.flush();
                pointOfContact.addPhone(phone2);
                phone2.addPointOfContact(pointOfContact);
            } catch (Exception e) {
                
applicationScopeBean.log("EmailStatelessBean.createPointOfContact(): exception 
persisting POINT OF CONTACT PHONE # 2");
                e.printStackTrace();
            }
            
        } // if (pointOfContactPersisted)
        
        return pointOfContactPersisted;
    }
    
    private List<Orders> findAllTemplates()  throws Exception {

        List<Orders> ordersList = null;
        Query q;

        try {
            q = em.createNamedQuery("Orders.findAllTemplates");
            q.setHint("eclipselink.query-results-cache", "true")
             .setHint("eclipselink.read-only", "true");
            ordersList = q.getResultList();
        } catch(Exception ex) {
            throw ex;
        }
        return ordersList;
    }
    
    private AddressType getAddressTypeByName (String name) {

        Query q;
        AddressType addressType;

        try {

            q = em.createNamedQuery("AddressType.findByAddressTypeName");
            q.setParameter("addressTypeName", name);
            addressType = (AddressType) q.getSingleResult();

        } catch (Exception e) {
            throw new EJBException(e);
        }

        return addressType;

    } // getAddressTypeByName

    private Customer getCustomerForCustomerId (Integer customerId) {

        Query q;
        Customer customer;

        try {

            q = em.createNamedQuery("Customer.findByCustomerId");
            q.setParameter("customerId", customerId);
            customer = (Customer) q.getSingleResult();

        } catch (NoResultException e) {
            customer = null;
        } catch (Exception e) {
            throw new EJBException(e);
        }

        return customer;

    } // getCustomerForCustomerId

    private EmailAddressType getEmailAddressTypeByName (String name) {

        Query q;
        EmailAddressType emailAddressType;

        try {

            q = 
em.createNamedQuery("EmailAddressType.findByEmailAddressTypeName");
            q.setParameter("emailAddressTypeName", name);
            emailAddressType = (EmailAddressType) q.getSingleResult();

        } catch (Exception e) {
            throw new EJBException(e);
        }

        return emailAddressType;

    } // getEmailAddressTypeByName

    private List<OrderCostDetails> getOrderCostDetailsForOrder(Integer id)  
throws Exception {
        List<OrderCostDetails> list;
        Query q;

        try {
            q = em.createNamedQuery("OrderCostDetails.findByOrderId")
                  .setParameter("orderId", id)
                  .setHint("eclipselink.query-results-cache", "true")
                  .setHint("eclipselink.read-only", "true");
            list = q.getResultList();
        } catch(Exception ex) {
            throw ex;
        }
        return list;
    }

    private PhoneType getPhoneTypeByName (String name) {

        Query q;
        PhoneType phoneType;

        try {

            q = em.createNamedQuery("PhoneType.findByPhoneTypeName");
            q.setParameter("phoneTypeName", name);
            phoneType = (PhoneType) q.getSingleResult();

        } catch (Exception e) {
            throw new EJBException(e);
        }

        return phoneType;

    } // getPhoneTypeByName

    private Orders getTemplate(String templateName) {
        Orders order = null;
        List<Orders> orders;
        try {
            orders = findAllTemplates();
            if (orders != null) {
                for (Orders o : orders) {
                    if (o.getTemplateId() != null &&
                        
o.getTemplateId().getTemplateName().contains(templateName)) {
                        order = o;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            applicationScopeBean.log("EmailStatelessBean.getTemplate(): 
exception getting list of Templates");
            e.printStackTrace();
        }
        return order;
    }

    private Users getUserByName (String name) {

        Query q;
        Users user;

        try {

            q = em.createNamedQuery("Users.findByUserName");
            q.setParameter("userName", name);
            user = (Users) q.getSingleResult();

        } catch (Exception e) {
            throw new EJBException(e);
        }

        return user;

    } // getUserByName

    private void initOrderCostDetails(OrderCostDetails ocd, Boolean yesNoFlags, 
Boolean charges,
                                      Boolean costValues, Boolean 
userModifiedValues,
                                      Boolean otherValues, Boolean 
checkForNullValues) {
        double doubleZero = 0.0;
        short shortZero = 0;
        Character yesNo = 'N';

        if (yesNoFlags) {
            // apply fuel surcharge to all trips, by default
            ocd.setApplyChargeFuelSurcharge('Y');
            ocd.setApplyChargeGratuity(yesNo);
            ocd.setApplyCurrentCharges(yesNo);
            ocd.setApplyChargeMeals('Y');
        }

        if (charges) {
            ocd.setChargeDeadMile(doubleZero);
            ocd.setChargeEachAdditionalHour(doubleZero);
            ocd.setChargeFirstHours(shortZero);
            ocd.setChargeFirstMiles(shortZero);
            ocd.setChargeFirstRate(doubleZero);
            ocd.setChargeFuelSurcharge(doubleZero);
            ocd.setChargeGratuity(doubleZero);
            ocd.setChargeLayover(doubleZero);
            ocd.setChargeLiveMile(doubleZero);
            ocd.setNbrOfPassengers(shortZero);
            ocd.setServiceAbbr(null);
            /*
             * add charge_meals to COMPANY or organization table
             *
             */
            ocd.setChargeMeals(25.00);
        }

        if (costValues) {
            ocd.setCostAdditionalDriver(doubleZero);
            ocd.setCostDays(doubleZero);
            ocd.setCostDeadMile(doubleZero);
            ocd.setCostFuelSurcharge(doubleZero);
            ocd.setCostGratuity(doubleZero);
            ocd.setCostLayover(doubleZero);
            ocd.setCostLiveMile(doubleZero);
            ocd.setCostMiles(doubleZero);
            ocd.setCostMilesOrDays(doubleZero);
            ocd.setSubtotal(doubleZero);
        }

        if (userModifiedValues) {
            ocd.setChargeAdditionalDriverHours(doubleZero);
            ocd.setChargeAdditionalDriverMiles(doubleZero);
            ocd.setCostMeals(doubleZero);
            ocd.setCostOther(doubleZero);
            ocd.setCostParking(doubleZero);
            ocd.setCostPermits(doubleZero);
            ocd.setCostTolls(doubleZero);
            ocd.setHoursPerDay(shortZero);
            ocd.setNbrOfAdditionalDriverHours(shortZero);
            ocd.setNbrOfAdditionalDriverMiles(shortZero);
            ocd.setNbrOfAdditionalDrivers(shortZero);
            ocd.setNbrOfDays(shortZero);
            ocd.setNbrOfDeadMiles(doubleZero);
            ocd.setNbrOfLayovers(shortZero);
            ocd.setNbrOfLiveMiles(doubleZero);
        }

        if (otherValues) {
            ocd.setCostDetailsId(1);
            ocd.setNbrOfVehicleOperators(shortZero);
            ocd.setNbrOfVehicles(shortZero);
        }

        if (checkForNullValues) {
            if (ocd.getChargeAdditionalDriverHours() == null) 
ocd.setChargeAdditionalDriverHours(doubleZero);
            if (ocd.getChargeAdditionalDriverMiles() == null) 
ocd.setChargeAdditionalDriverMiles(doubleZero);
            if (ocd.getCostMeals() == null) ocd.setCostMeals(doubleZero);
            if (ocd.getCostOther() == null) ocd.setCostOther(doubleZero);
            if (ocd.getCostParking() == null) ocd.setCostParking(doubleZero);
            if (ocd.getCostPermits() == null) ocd.setCostPermits(doubleZero);
            if (ocd.getCostTolls() == null) ocd.setCostTolls(doubleZero);
            if (ocd.getHoursPerDay() == null) ocd.setHoursPerDay(shortZero);
            if (ocd.getNbrOfAdditionalDriverHours() == null) 
ocd.setNbrOfAdditionalDriverHours(shortZero);
            if (ocd.getNbrOfAdditionalDriverMiles() == null) 
ocd.setNbrOfAdditionalDriverMiles(shortZero);
            if (ocd.getNbrOfAdditionalDrivers() == null) 
ocd.setNbrOfAdditionalDrivers(shortZero);
            if (ocd.getNbrOfDays() == null) ocd.setNbrOfDays(shortZero);
            if (ocd.getNbrOfDeadMiles() == null) 
ocd.setNbrOfDeadMiles(doubleZero);
            if (ocd.getNbrOfLayovers() == null) ocd.setNbrOfLayovers(shortZero);
            if (ocd.getNbrOfLiveMiles() == null) 
ocd.setNbrOfLiveMiles(doubleZero);
            if (ocd.getNbrOfVehicleOperators() == null) 
ocd.setNbrOfVehicleOperators(shortZero);
            if (ocd.getNbrOfVehicles() == null) ocd.setNbrOfVehicles(shortZero);
        }

    }

    private Boolean processAirportShuttleRequest(jsonAirportShuttleResults 
request) {
        if (request == null) {
            return false;
        }
        Boolean completed = true;
        if (debug) {
            
applicationScopeBean.log("EmailStatelessBean.processAirportShuttleRequest(): 
BEGIN " + new Date());
        }
        if (!createOrderForAirportShuttle(request, 
request.getFlight1Details())) {
            completed = false;
        }
        String msg = (completed ? "SUCCESSFULLY" : "FAILED");
        
applicationScopeBean.log("EmailStatelessBean.processAirportShuttleRequest(): 
ADD Airport Shuttle - Flight # 1 " + msg +
                                 " for " + 
request.getFlight1Details().getFlightDate());
        if (completed) {
            if (request.getFlight2DetailsExist().equals("Yes")) {
                completed = createOrderForAirportShuttle(request, 
request.getFlight2Details());
                msg = (completed ? "SUCCESSFULLY" : "FAILED");
                
applicationScopeBean.log("EmailStatelessBean.processAirportShuttleRequest(): 
ADD Airport Shuttle - Flight # 2 " + msg +
                                         " for " + 
request.getFlight2Details().getFlightDate());
            }
        }
        if (debug) {
            
applicationScopeBean.log("EmailStatelessBean.processAirportShuttleRequest(): 
END " + new Date());
        }
        return completed;
    }
    
    private void setDefaultValues(Orders order) {
        Character defaultChar = 'N';
        Date defaultNoDate = null;
        double doubleZero = 0.0;
        short shortZero = 0;

        order.setTripDateTime(DateTime.now().withMinuteOfHour(0).toDate());
        order.setReportDateTime(defaultNoDate);
        order.setReturnDateTime(DateTime.now().withMinuteOfHour(0).toDate());

        if (order.getBalance() == null)
            order.setBalance(doubleZero);
        if (order.getDeposit() == null)
            order.setDeposit(doubleZero);
        if (order.getDiscount() == null)
            order.setDiscount(doubleZero);
        if (order.getDiscountRate() == null)
            order.setDiscountRate(doubleZero);
        if (order.getTotalCost() == null)
            order.setTotalCost(doubleZero);

        order.setDepositPaid(defaultChar);
        order.setDepositPaidDate(defaultNoDate);

        order.setPaidInFull(defaultChar);
        order.setPaidInFullDate(defaultNoDate);

        order.setCancelled(defaultChar);
        order.setCancelledDate(defaultNoDate);

        order.setConfirmed(defaultChar);
        order.setConfirmedDate(defaultNoDate);

        order.setContractSent(defaultChar);
        order.setContractSentDate(defaultNoDate);

        order.setInvoiceSent(defaultChar);
        order.setInvoiceSentDate(defaultNoDate);

        order.setQuoteSent(defaultChar);
        order.setQuoteSentDate(defaultNoDate);

        order.setIntrastate(defaultChar);
        order.setPassengers(shortZero);
        order.setCreatedBy(null);
    }

}

                
> @Stateless EJB with @Schedule method and single EntityManager/transaction 
> does not perform well and holds transaction
> ---------------------------------------------------------------------------------------------------------------------
>
>                 Key: OPENEJB-1968
>                 URL: https://issues.apache.org/jira/browse/OPENEJB-1968
>             Project: OpenEJB
>          Issue Type: Bug
>          Components: ejb31
>    Affects Versions: 4.5.0
>         Environment: TomEE 1.5.1
> Windows Server 2003 32bit 4GB RAM
>            Reporter: Howard W. Smith, Jr.
>              Labels: @Stateless, EJB, entitymanager, transaction
>         Attachments: EmailStatelessBean.java, tomcat7-stderr.2012-12-12.log
>
>   Original Estimate: 504h
>  Remaining Estimate: 504h
>
> After implementing 'workaround' option # 1 in my previous email (below), the 
> test results were really really bad. :(
> for 4 emails, it took 30 minutes to insert the data into the database, and 
> then it seemed as though the single @Stateless EJB held onto the transaction, 
> even after the @Schedule method, getEmails(), was done and exited.
> Should I file a JIRA? I would assume that the @Stateless bean would 'let go' 
> of the transaction, but transaction remained opened. Maybe, I should have 
> issued a entityManager.flush() after completing each email, but I did flush() 
> a lot throughout the process.
> Please note that this machine is Windows Server 2003 32bit 4GB RAM, and it 
> takes 10 to 15 minutes to insert data from 2 emails (which is a very small 
> amount of data embedded in the email). I could not select any data from 
> database after login. I had to shutdown TomEE.
> Also, note, when I originally developed this, one @Stateless EJB with 1 
> entity manager, it took 2 seconds on Windows Server 2008 64bit 16GB RAM, and 
> it did not hold the transaction (or database locks). also, i could select 
> data afterwards.
> I still need to try what David mentioned, but it's been an all-nighter for 
> me, so i need to stop right here for now.
> I think I will open a JIRA for this.
> On Tue, Dec 11, 2012 at 10:10 PM, Howard W. Smith, Jr. 
> <[email protected]> wrote:
> Shaking my head... test results were not good at all.
> 1. @StatelessEJB EmailStatelessBean has @Schedule getEmails()
> 2. @EmailStatelessBean has multiple @EJB references to @Stateless 
> (sessionfacade) classes that are the DAO classes
> 3. EmailStatelessBean gets invoked when triggered by @Schedule
> 4. EmailStatelessBean execution locks the tables, still, and locks up the 
> entire app, and seems to take longer...since endusers (myself) are making 
> requests against database (and web app).
> 5. Last but not least, EmailStatelessBean failed to commit the changes; 
> transaction rolled back for EmailStatelessBean as well as enduser requests.
> So, my workaround options include the following:
> 1. EmailStatelessBean, when invoked by @Schedule method, will check the CDI 
> @ApplicationScoped bean (ApplicationScopeBean), and see if any endusers are 
> logged in; i developed a sessionInfo class that is updated everytime enduser 
> does a HTTP request; if any endusers are logged in, then I can use Atmosphere 
> (PrimeFaces Push) to push a message to the endusers, notifying them to 
> 'please logout, as there are customer requests pending that need to be 
> retrieved and inserted into the web app's database', and EmailStatelessBean 
> will 'return' (or exit) and not perform the operation. This way, everytime 
> @Schedule invokes the bean method, it will continue to check for an available 
> time to perform the get-emails-and-insert-into-database operation. Also, I'll 
> set when EmailStatelessBean begins the operation, then I'll set flag on 
> @ApplicationScoped bean (insertingCustomerRequestsIntoDatabase = true); this 
> flag will be checked when endusers attempt to login web app, and FacesMessage 
> will be displayed, Please login a few minutes later as system is inserting 
> customer requests into database.
> 2. Another option would be to send a message to all clients via Atmosphere 
> (PrimeFaces Push), and the UI will be locked immediately, and user will be 
> required to wait.
> Honestly, I don't like either of these approaches, but I think the endusers 
> will accept the 1st option (above). If I go with 1st approach, then I may 
> revert back to single transaction, which will complete the entire operation 
> much faster than multiple transactions (via multiple EJB DAO classes).
> As you can see, I don't have enough experience locking database for such a 
> batch operation as this. I know the endusers want the customer requests to 
> show up into the database 'immediately', and they want to know when it 
> happens. Right now, this is my only option until I redesign the business 
> website to interface directly with the web app. right now, the web app is 
> 'only' used by 'personnel' (the owners of the business...which is my family). 
> hahaha :)
> They love the app (honestly, they liked the speed and reliability of the web 
> app when it was on Glassfish), but I'm doing all i can to win them over with 
> TomEE. :)
> Your thoughts, please.
> Thanks,
> Howard

--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: http://www.atlassian.com/software/jira

Reply via email to