CPD Results

The following document contains the results of PMD's CPD 5.3.2.

Duplications

File Project Line
org/myorg/jpatickets/ejb/EventMgmtEJB.java EJB::JPA Tickets Lab::Exercise::EJB 31
org/myorg/jpatickets/ejb/EventMgmtEJB.java EJB::JPA Tickets Lab::Solution::EJB 33
    private static final Logger logger = LoggerFactory.getLogger(EventMgmtEJB.class);
    
    //@PersistenceContext(unitName="jpatickets-labex")
    private EntityManager em;
    
    private EventMgmtDAO edao;
    private EventMgmt eventMgmt;
    
    @PostConstruct
    public void init() {
        logger.debug("*** EventMgmtEJB:init({}) ***", super.hashCode());
        
        edao = new EventMgmtDAOImpl();
        ((EventMgmtDAOImpl)edao).setEntityManager(em);
        VenueDAOImpl vdao = new VenueDAOImpl();
            vdao.setEntityManager(em);
        eventMgmt = new EventMgmtImpl();
        ((EventMgmtImpl)eventMgmt).setEventDAO(edao);
        ((EventMgmtImpl)eventMgmt).setVenueDAO(vdao);
    }
    
    @PreDestroy
    public void destroy() {
        logger.debug("*** EventMgmtEJB:destroy({}) ***", super.hashCode()); 
    }
    

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Event createEvent(Event event, Venue venue) throws UnavailableException {
        return eventMgmt.createEvent(event, venue);
    }
    
    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public Event getEvent(int id) {
        logger.debug("getEvent({})", id);
        return eventMgmt.getEvent(id);
    }
    
    @Override
    public Event getEventCleansed(int id) {
        logger.debug("getCleansedEvent({})", id);
        Event event = getEvent(id);
        return toCleansed(event);
    }
    
    private Event toCleansed(Event bo) {
        Event pojo = new Event(bo.getId());
        pojo.setName(bo.getName());
        pojo.setStartTime(bo.getStartTime());
        List<Ticket> tickets = new ArrayList<Ticket>(bo.getTickets().size());
        for (Ticket t: bo.getTickets()) {
            toCleansed(t, pojo);
        }
        pojo.setTickets(tickets);
        return pojo;
    }
    
    private Ticket toCleansed(Ticket bo, Event event) {
        //example cleansing is stopping here for the example
        Ticket pojo = new Ticket(event, bo.getSeat());
        pojo.setPrice(bo.getPrice());
        pojo.setSold(bo.isSold());
        return pojo;
    }
    
    @Override
    public Event getEventTouchedSome(int id) {
        logger.debug("getEventTouchedSome({})", id);
        Event event = getEvent(id);
        //touch the ticket collection to load tickets prior to marshaling back
        event.getTickets().size();
        return event;
    }
    
    @Override
    public Event getEventTouchedMore(int id) {
        logger.debug("getEventTouchedMore({})", id);
        Event event = getEvent(id);
        //touch ticket collection and all seats to load both prior to marshaling back
        event.getTickets().size();
        event.getVenue().getName();
        for (Ticket t: event.getTickets()) {
            t.getSeat().getPosition();
        }
        return event;
    }
    
    @Override
    public Event getEventFetchedSome(int id) {
        logger.debug("getEventFetchedSome({})", id);
        Event event = eventMgmt.fetchEventTickets(id);
        return event;
    }
    
    @Override
    public Event getEventFetchedMore(int id) {
        logger.debug("getEventFetchedMore({})", id);
        Event event = eventMgmt.fetchEventTicketsSeats(id);
        return event;
    }
    
    @Override
    public EventDTO getEventLazyDTO(int id) {
        logger.debug("getEventLazyDTO({})", id);
        Event event = eventMgmt.getEvent(id);
        return toEventDTO(event);
    }
    
    private EventDTO toEventDTO(Event event) {
        EventDTO dto = new EventDTO();
        dto.setId(event.getId());
        dto.setEventName(event.getName());
        dto.setVenueName(event.getVenue().getName());
        dto.setStartTime(event.getStartTime());
        dto.setNumTickets(event.getTickets().size());
        return dto;
    }
    
    @Override
    public EventDTO getEventFetchedDTO(int eventId) {
        logger.debug("getEventFetchedDTO({})", eventId);
        Map<String, Object> dtoData = edao.fetchEventDTOData(eventId);
        return toEventDTO(dtoData);
    }
    
    private EventDTO toEventDTO(Map<String, Object> dtoData) {
        EventDTO dto = new EventDTO();
        Event event = (Event) dtoData.get(EventMgmtDAO.EVENT);
        String venueName = (String) dtoData.get(EventMgmtDAO.VENUE_NAME);
        int numTickets = (Integer) dtoData.get(EventMgmtDAO.NUM_TICKETS);
        dto.setId(event.getId());
        dto.setEventName(event.getName());
        dto.setStartTime(event.getStartTime());
        dto.setVenueName(venueName);
        dto.setNumTickets(numTickets);
        return dto;
    }
    
}
File Project Line
org/myorg/jpatickets/dao/EventMgmtDAOImpl.java EJB::JPA Tickets Lab::Exercise::Impl 20
org/myorg/jpatickets/dao/EventMgmtDAOImpl.java EJB::JPA Tickets Lab::Solution::Impl 20
public class EventMgmtDAOImpl implements EventMgmtDAO {
    EntityManager em;
    
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @Override
    public Event createEvent(Event event) {
        em.persist(event);
        return event;
    }
    
    @Override
    public Event getEvent(int eventId) {
        return em.find(Event.class, eventId);
    }
    
    @Override
    public Event fetchEventTickets(int id) {
        List<Event> events = em.createNamedQuery("JPATicketEvent.fetchEventTickets", 
                Event.class)
                .setParameter("eventId", id)
                .getResultList();
        return events.isEmpty() ? null : events.get(0);
    }    
    
    @Override
    public Event fetchEventTicketsSeats(int id) {
        List<Event> events = em.createNamedQuery("JPATicketEvent.fetchEventTicketsSeats", 
                Event.class)
                .setParameter("eventId", id)
                .getResultList();
        return events.isEmpty() ? null : events.get(0);
    }
    
    @Override
    public Map<String, Object> fetchEventDTOData(int eventId) {
        @SuppressWarnings("unchecked")
        List<Object[]> rows = em.createNamedQuery("JPATicketEvent.fetchEventDTO")
                .setParameter("eventId", eventId)
                .getResultList();
        
        Map<String, Object> dtoData = new HashMap<String, Object>();
        if (!rows.isEmpty()) {
            Object[] row = rows.get(0);
            Event event = (Event) row[0];
            String venueName = (String) row[1];
            Number numTickets = (Number) row[2];
            dtoData.put(EVENT, event);
            dtoData.put(VENUE_NAME, venueName);
            dtoData.put(NUM_TICKETS, numTickets.intValue());
        }
        return dtoData;
    }
    
    @Override
    public List<Seat> findSeats(Event event, String section, Integer row,
            Integer position, int offset, int limit) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Seat> qdef = cb.createQuery(Seat.class);
        Root<Ticket> t = qdef.from(Ticket.class);
        Join<Ticket, Event> e = t.join("event");
        Join<Ticket, Seat> s = t.join("seat");
        
        Predicate pred = cb.conjunction();
        List<Expression<Boolean>> expr = pred.getExpressions();
        if (section != null) {
            expr.add(cb.equal(s.get("pk").get("section"), section));
        }
        if (row !=null) {
            expr.add(cb.equal(s.get("pk").get("row"), row));
        }
        if (position !=null) {
            expr.add(cb.equal(s.get("pk").get("position"), position));
        }
        
        qdef.select(s).where(cb.and(cb.equal(e, event), pred)).orderBy(cb.asc(t.get("price")));
        TypedQuery<Seat> query = em.createQuery(qdef);
        if (offset > 0) {
            query.setFirstResult(offset);
        }
        if (limit > 0) {
            query.setMaxResults(limit);
        }
        
        return query.getResultList();
    }
    
    @Override
    public List<Ticket> findTickets(Event event, List<Seat> seats) {
        return em.createNamedQuery("JPATicketTicket.findTickets", 
                Ticket.class)
                .setParameter("seats", seats)
                .getResultList();
    }
}
File Project Line
org/myorg/jpatickets/bo/Seat.java EJB::JPA Tickets Lab::Exercise::Impl 7
org/myorg/jpatickets/bo/Seat.java EJB::JPA Tickets Lab::Solution::Impl 7
@SuppressWarnings("serial")
@Entity
@Table(name="JPATICKET_SEAT")
@NamedQueries({
    @NamedQuery(name = "JPATicketSeat.getSeatsForVenue", 
            query = "select s from Seat s where s.venue = :venue")
})
public class Seat implements Serializable {
    @EmbeddedId
    private SeatPK pk;
    
    @MapsId("venueId")
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="VENUE_ID")
    private Venue venue;
    
    protected Seat() {}
    public Seat(Venue venue, String section, int row, int position) {
        this.venue = venue;
        this.pk = new SeatPK(venue==null ? null : venue.getId(), section, row, position);
    }

    public Venue getVenue()    { return venue; }
    public String getVenueId() { return pk==null ? null : pk.getVenueId(); }
    public String getSection() { return pk==null ? null : pk.getSection(); }
    public int getRow()        { return pk==null ? 0 : pk.getRow(); }
    public int getPosition()   { return pk==null ? 0 : pk.getPosition(); }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + getPosition();
        result = prime * result + getRow();
        result = prime * result + ((getSection() == null) ? 0 : getSection().hashCode());
        result = prime * result + ((getVenueId() == null) ? 0 : getVenueId().hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if (obj == null) { return false; }
        if (getClass() != obj.getClass()) { return false; }
        Seat other = (Seat) obj;
        return (getPosition() == other.getPosition()) &&
           (getRow() != other.getRow()) &&
           (getSection() == null ? other.getSection()==null : getSection().equals(other.getSection())) &&
           (getVenueId() ==null ? other.getVenueId()==null : venue.getId().equals(other.getVenueId()));
    }
    
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Seat [venue=").append(getVenueId())
                .append(", section=").append(getSection())
                .append(", row=").append(getRow())
                .append(", position=").append(getPosition())
                .append("]");
        return builder.toString();
    }
}
File Project Line
org/myorg/jpatickets/ejb/TicketsInitTxEJB.java EJB::JPA Tickets Lab::Exercise::EJB 39
org/myorg/jpatickets/ejb/TicketsInitTxEJB.java EJB::JPA Tickets Lab::Solution::EJB 39
    @PersistenceUnit(unitName=PU_NAME)
    private EntityManagerFactory emf;
    
    @Resource
    private UserTransaction utx;
    
    private String dropScript;
    private String createScript;

    @PostConstruct
    public void init() {
        StringWriter createScriptWriter = new StringWriter();
        StringWriter dropScriptWriter = new StringWriter();
        Map<String, Object> props = new HashMap<String, Object>();
        props.put("javax.persistence.schema-generation.scripts.create-database-schemas", "true");
        props.put("javax.persistence.schema-generation.scripts.action", "drop-and-create");
        props.put("hibernate.id.new_generator_mappings", "true"); //tell JSE schemagen to use SEQUENCE for @Id=AUTO
        props.put("javax.persistence.schema-generation.scripts.create-target", createScriptWriter);
        props.put("javax.persistence.schema-generation.scripts.drop-target", dropScriptWriter);
        Persistence.generateSchema(PU_NAME, props);
        dropScript = dropScriptWriter.toString();
        createScript = createScriptWriter.toString();
        logger.debug("createScript={}", createScript);
        logger.debug("dropScript={}", dropScript);
    }
    
    private List<String> getCommands(String script) {
        List<String> commands = new ArrayList<String>();
        for (String line : script.split("\n")) {
            commands.add(line);
        }
        return commands;
    }

    @javax.ejb.Lock(LockType.WRITE)
    public int dropDB() {
        logger.info("*** dropDB ***");
        int updates=0;
        EntityManager em = emf.createEntityManager();
        try {
            for (String nativeSQLCommand : getCommands(dropScript)) {
                try {
                    utx.begin();
                    em.joinTransaction();
                    updates += em.createNativeQuery(nativeSQLCommand).executeUpdate();
                    utx.commit();
                } catch (Exception ex) {
                    try { utx.rollback(); } catch (Exception ex2) { throw new EJBException(ex2); }
                    logger.warn("error executing SQL:" + ex + ", " + nativeSQLCommand);
                    //keep going
                }
            }
        } finally {
            em.close();
        }
        return updates;
    }
    
    @javax.ejb.Lock(LockType.WRITE)
    public int createDB() {
        logger.info("*** createDB ***");
        int updates=0;
        EntityManager em = emf.createEntityManager();
        try {
            utx.begin();
            em.joinTransaction();
            //all in one transaction
            for (String nativeSQLCommand : getCommands(createScript)) {
                updates += em.createNativeQuery(nativeSQLCommand).executeUpdate();
            }
            utx.commit();
        } catch (Exception ex) {
            logger.warn("error executing SQL:" + ex);
            try { utx.rollback(); } catch (Exception ex2) { throw new EJBException(ex2); }
        } finally {
            em.close();
        }
        return updates;
    }
}
File Project Line
org/myorg/jpatickets/bo/Address.java EJB::JPA Tickets Lab::Exercise::Impl 8
org/myorg/jpatickets/bo/Address.java EJB::JPA Tickets Lab::Solution::Impl 8
@Embeddable
public class Address implements Serializable {
    private static final long serialVersionUID = 5678018330323499890L;
    @Column(name="STREET", length=20)
    private String street;
    @Column(name="CITY", length=20)
    private String city;
    @Column(name="STATE", length=2)
    private String state;
    @Column(name="POSTAL_CODE")
    private int zipCode;
    
    public String getStreet() { return street; }
    public void setStreet(String street) {
        this.street = street;
    }
    public Address withStreet(String street) {
        setStreet(street);
        return this;
    }
    
    public String getCity() { return city; }
    public void setCity(String city) {
        this.city = city;
    }
    public Address withCity(String city) {
        setCity(city);
        return this;
    }
    
    public String getState() { return state; }
    public void setState(String state) {
        this.state = state;
    }
    public Address withState(String state) {
        setState(state);
        return this;
    }

    public int getZipCode() { return zipCode; }
    public void setZipCode(int zipCode) {
        this.zipCode = zipCode;
    }
    public Address withZipCode(int zipCode) {
        setZipCode(zipCode);
        return this;
    }
    
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((city == null) ? 0 : city.hashCode());
        result = prime * result + ((state == null) ? 0 : state.hashCode());
        result = prime * result + ((street == null) ? 0 : street.hashCode());
        result = prime * result + zipCode;
        return result;
    }
    
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if (obj == null) { return false; }
        if (getClass() != obj.getClass()) { return false; }
        Address other = (Address) obj;
        
        return (city == null ? other.city == null : city.equals(other.city)) &&
            (state == null ? other.state == null : state.equals(other.state)) &&
            (street == null ? other.street == null : street.equals(other.street)) &&
            (zipCode == other.zipCode);
    }
    
    
}
File Project Line
org/myorg/encconfig/ejb/AuditorBase.java EJB::ENC Config Lab::Exercise:EJB 20
org/myorg/encconfig/ejb/AuditorBase.java EJB::ENC Config Lab::Solution::EJB 20
public abstract class AuditorBase {
	private Logger log_;
	private boolean publishJMS_;
	private EntityManager em_;
	private ConnectionFactory cf_;
	private Topic topic_;

	public void setLog(Logger log) { this.log_ = log; }
	public void setEntityManager(EntityManager em) { this.em_ = em; }
	public void setConnectionFactory(ConnectionFactory cf) { this.cf_ = cf; }
	public void setTopic(Topic topic) { this.topic_ = topic; }
	public void setPublishJMS(boolean publishJMS) { 
		this.publishJMS_ = publishJMS; 
	}
	public int audit(String message) {
		AuditRecord rec = new AuditRecord(new Date(), message);
		int actions=0;
		if (persistRecord(rec) != null) {
			actions += 1;
		}
		if (publishJMS_ && cf_ != null) {
			publishRecord(rec);
			actions += 1;
		}
		return actions;
	}
	
	protected AuditRecord persistRecord(AuditRecord rec) {
		if (em_!=null) {
			em_.persist(rec);
			log_.debug("message persisted:{}", rec);
			return rec;		
		}
		return null;
	}
	
	
	protected void publishRecord(AuditRecord rec) {
		Connection connection=null;
		Session session = null;
		MessageProducer publisher = null;
		try {
			connection = cf_.createConnection();
			session = connection.createSession(
					false, Session.AUTO_ACKNOWLEDGE);
			TextMessage msg = session.createTextMessage(rec.getMessage());
			publisher = session.createProducer(topic_);
			publisher.send(msg);
			log_.debug("message sent:{}", msg);
		} catch (JMSException ex) {
			log_.error("error sending JMS message", ex);
			throw new EJBException("error sending JMS message:"+ex);
		} finally {
			close(connection, session);
		}
	}
	
	protected void close(Connection conn, Session session) {
		try { if (session != null) { session.close(); } } 
		catch (JMSException ex) {log_.info("error closing session", ex); }
		try { if (conn != null) { conn.close(); } } 
		catch (JMSException ex) {log_.info("error closing connection", ex); }
	}
	protected void close(Context jndi) {
		try { if (jndi != null) { jndi.close(); } } 
		catch (NamingException ex) {log_.info("error closing jndi", ex); }
	}

}
File Project Line
org/myorg/jpatickets/bo/SeatPK.java EJB::JPA Tickets Lab::Exercise::Impl 8
org/myorg/jpatickets/bo/SeatPK.java EJB::JPA Tickets Lab::Solution::Impl 8
@Embeddable
public class SeatPK implements Serializable {
    private static final long serialVersionUID = -5824145862784177861L;
    //mapped to FK
    private String venueId;
    @Column(name="SECTION", length=6)
    private String section;
    @Column(name="ROW")
    private int row;
    @Column(name="POSTION")
    private int position;
    
    protected SeatPK() {}

    public SeatPK(String venueId, String section, int row, int position) {
        this.venueId = venueId;
        this.section = section;
        this.row = row;
        this.position = position;
    }
    
    public String getVenueId() { return venueId; }
    public String getSection() { return section; }
    public int getRow() { return row; }
    public int getPosition() { return position; }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + position;
        result = prime * result + row;
        result = prime * result + ((section == null) ? 0 : section.hashCode());
        result = prime * result + ((venueId == null) ? 0 : venueId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if (obj == null) { return false; }
        if (getClass() != obj.getClass()) { return false; }
        SeatPK other = (SeatPK) obj;
        return (position == other.position) &&
            (row == other.row) &&
            (section==null ? other.section==null : section.equals(other.section))  &&
            (venueId==null ? other.venueId==null : venueId.equals(other.venueId));
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("SeatPK [venueId=").append(venueId)
            .append(", section=").append(section)
            .append(", row=").append(row)
            .append(", position=").append(position)
            .append("]");
        return builder.toString();
    }

    
}
File Project Line
org/myorg/jpatickets/bo/Event.java EJB::JPA Tickets Lab::Exercise::Impl 47
org/myorg/jpatickets/bo/Event.java EJB::JPA Tickets Lab::Solution::Impl 47
public class Event /* implements Serializable */ {
    @Id @GeneratedValue
    @Column(name="EVENT_ID")
    private int id;
    
    @Column(name="EVENT_NAME", length=40, nullable=false)
    private String name;
    
    @ManyToOne(fetch=FetchType.LAZY, optional=false)
    @JoinColumn(name="VENUE_ID", nullable=false, updatable=false)
    private Venue venue;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="START_TIME")
    private Date startTime;
    
    @OneToMany(mappedBy="event", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
    private List<Ticket> tickets;
    
    protected Event() { }
    public Event(Venue venue) { 
        this.venue=venue;
    }
    public Event(int id) { this.id=id; }

    public int getId() { return id; }
    public Venue getVenue() { return venue; }

    public String getName() { return name; }
    public void setName(String name) {
        this.name = name;
    }
    public Event withName(String name) {
        setName(name);
        return this;
    }
    
    public Date getStartTime() { return startTime; }
    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
    public Event withStartTime(Date startTime) {
        setStartTime(startTime);
        return this;
    }

    public List<Ticket> getTickets() { return tickets; }
    public void setTickets(List<Ticket> tickets) {
        this.tickets = tickets;
    }
    public Event withTicket(Ticket ticket) {
        if (tickets==null) {
            tickets = new LinkedList<Ticket>();
        }
        if (ticket!=null) {
            tickets.add(ticket);
        }
        return this;
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Event [id=").append(id)
                .append(", name=").append(name)
                .append(", venue=").append(venue==null ? null : venue.getName())
                .append(", startTime=").append(startTime)
                .append("]");
        return builder.toString();
    }
}
File Project Line
org/myorg/jpatickets/bl/EventMgmtImpl.java EJB::JPA Tickets Lab::Exercise::Impl 13
org/myorg/jpatickets/bl/EventMgmtImpl.java EJB::JPA Tickets Lab::Solution::Impl 13
public class EventMgmtImpl implements EventMgmt {
    private EventMgmtDAO edao;
    private VenueDAO vdao;
    
    public void setEventDAO(EventMgmtDAO edao) {
        this.edao = edao;
    }
    public void setVenueDAO(VenueDAO vdao) {
        this.vdao = vdao;
    }

    @Override
    public Event createEvent(Event event, Venue venue) throws UnavailableException {
        BigDecimal maxPrice = new BigDecimal(1000);
        List<Seat> seats = vdao.getSeatsForVenue(venue, 0, 0);
        for (Seat seat: seats) {
            Ticket ticket = new Ticket(event, seat);
            BigDecimal discount = new BigDecimal(seat.getRow()*.1);
            ticket.setPrice(maxPrice.subtract(maxPrice.multiply(discount)));
            event.withTicket(ticket);
        }
        return edao.createEvent(event);
    }

    @Override
    public Event getEvent(int id) {
        return edao.getEvent(id);
    }
    @Override
    public Event fetchEventTickets(int id) {
        return edao.fetchEventTickets(id);
    }
    @Override
    public Event fetchEventTicketsSeats(int id) {
        return edao.fetchEventTicketsSeats(id);
    }

    @Override
    public List<Seat> findSeats(Event event, String section, Integer row, Integer position, int offset, int limit) {
        return edao.findSeats(event, section, row, position, offset, limit);
    }
    
    @Override
    public List<Ticket> getTickets(Event event, List<Seat> seats) {
        return edao.findTickets(event, seats);
    }

    @Override
    public List<Ticket> reserveSeats(Event event, List<Seat> seats) throws UnavailableException {
        if (event==null) { throw new IllegalArgumentException("no event provided"); }
        if (seats==null) { throw new IllegalArgumentException("no seat selected"); }

        List<Ticket> tickets = getTickets(event, seats);
        for (Ticket ticket: tickets) {
            if (ticket.isSold()) {
                throw new UnavailableException(String.format("seat %s already sold", ticket.getSeat()));
            } else {
                ticket.setSold(true);
            }
        }
        return tickets;
    }
}
File Project Line
org/myorg/jpatickets/bo/Venue.java EJB::JPA Tickets Lab::Exercise::Impl 7
org/myorg/jpatickets/bo/Venue.java EJB::JPA Tickets Lab::Solution::Impl 7
@SuppressWarnings("serial")
@Entity
@Table(name="JPATICKETS_VENUE")
public class Venue implements Serializable {
    @Id
    @Column(name="VENUE_ID", length=3)
    private String id;
    
    @Column(name="NAME", length=20, unique=true)
    private String name;
    
    @Embedded
    private Address address;

    public Venue() {}
    public Venue(String id) { this.id = id; }    
    public String getId() { return id; }

    public String getName() { return name; }
    public void setName(String name) {
        this.name = name;
    }
    public Venue withName(String name) {
        setName(name);
        return this;
    }

    public Address getAddress() { return address; }
    public void setAddress(Address address) {
        this.address = address;
    }
    public Venue withAddress(Address address) {
        setAddress(address);
        return this;
    }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if (obj == null) { return false; }
        if (getClass() != obj.getClass()) { return false; }
        Venue other = (Venue) obj;
        
        return (id == null ? other.id == null : id.equals(other.id)) &&
           (name == null ? other.name == null : name.equals(other.name));
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Venue [id=").append(id)
                .append(", name=").append(name)
                .append(", address=").append(address)
                .append("]");
        return builder.toString();
    }
}
File Project Line
org/myorg/jpatickets/bo/Ticket.java EJB::JPA Tickets Lab::Exercise::Impl 8
org/myorg/jpatickets/bo/Ticket.java EJB::JPA Tickets Lab::Solution::Impl 8
@SuppressWarnings("serial")
@Entity
@Table(name="JPATICKETS_TICKET")
@NamedQueries({
    @NamedQuery(name="JPATicketTicket.findTickets", 
        query="select t from Ticket t where t.seat in :seats")
})
@IdClass(TicketPK.class)
public class Ticket implements Serializable {
    @Id
    @ManyToOne(fetch=FetchType.EAGER, optional=false)
    @JoinColumn(name="EVENT_ID")
    private Event event;
    
    @Id
    @OneToOne(
            //fetch=FetchType.EAGER,
            fetch=FetchType.LAZY,
            optional=false)
    @JoinColumns({
        @JoinColumn(name="VENUE_ID"),
        @JoinColumn(name="SECTION"),
        @JoinColumn(name="ROW"),
        @JoinColumn(name="POSITION"),
    })
    private Seat seat;
    
    @Column(name="PRICE", precision=7, scale=2)
    private BigDecimal price;
    
    @Column(name="SOLD", nullable=false)
    private boolean sold;

    protected Ticket() {}    
    public Ticket(Event event, Seat seat) {
        this.event = event;
        this.seat = seat;
    }

    public Event getEvent()   { return event; }
    public Seat getSeat()     { return seat; }
    
    public BigDecimal getPrice() { return price; }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
    
    public boolean isSold() { return sold; }
    public void setSold(boolean sold) {
        this.sold = sold;
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Ticket [event=").append(event)
                .append(", seat=").append(seat)
                .append(", price=").append(price)
                .append(", sold=").append(sold)
                .append("]");
        return builder.toString();
    }
    
    
}
File Project Line
ejava/examples/asyncmarket/web/BuyerHandlerServlet.java Async::Async Market::WAR 71
ejava/examples/asyncmarket/web/SellerHandlerServlet.java Async::Async Market::WAR 65
                buyer = jndi.getBuyer();
            }        
            if (userMgmt == null) {
                userMgmt = jndi.getUserMgmt();
            }        
        }
        catch (Exception ex) {
            log.fatal("error initializing handler", ex);
            throw new ServletException("error initializing handler", ex);
        }
        finally {
        	if (jndi != null) { jndi.close(); }
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) 
        throws ServletException, IOException {
        log.debug("doGet() called");
        String command = request.getParameter(COMMAND_PARAM);
        log.debug("command=" + command);
        try {            
            if (command != null) {
                Handler handler = handlers.get(command);
                if (handler != null) {
                    log.debug("handler=" + handler);
                    handler.handle(request, response);
                }
                else {
                    request.setAttribute("handlers", handlers);
                    RequestDispatcher rd = 
                        getServletContext().getRequestDispatcher(
                            UNKNOWN_COMMAND_URL);
                            rd.forward(request, response);
                }
            }
            else {
                throw new Exception("no " + COMMAND_PARAM + " supplied"); 
            }
        }
        catch (Exception ex) {
            request.setAttribute(EXCEPTION_PARAM, ex);
            RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    UNKNOWN_COMMAND_URL);
                    rd.forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response) 
        throws ServletException, IOException {
        log.debug("doPost() called, calling doGet()");
        doGet(request, response);
    }

    public void destroy() {
        log.debug("destroy() called");
    }
    
    private abstract class Handler {
        protected static final String RESULT_PARAM = "result";
        protected static final String MAINMENU_URL = 
            "/index.jsp";
        protected static final String DISPLAYUSER_URL = 
            "/WEB-INF/content/DisplayUser.jsp";
        protected static final String DISPLAYITEM_URL = 
            "/WEB-INF/content/DisplayItem.jsp";
        protected static final String DISPLAYITEMS_URL = 
File Project Line
ejava/jpa/example/validation/Address1.java JPA::Validation::Examples 16
ejava/jpa/example/validation/Address2.java JPA::Validation::Examples 21
public class Address1 {
	@Id @GeneratedValue
	private int id;
		
	@Column(name="STREET", length=32, nullable=false)
	@NotNull(message="street not supplied")
	@Size(max=32, message="street name too large", groups=DBChecks.class)
	@Pattern(regexp="^[0-9A-Za-z\\ ]+$", groups=DataChecks.class, 
	         message="street must be numbers and letters")
	private String street;
	
	@Column(name="CITY", length=20, nullable=false)
	@NotNull(message="city not supplied")
	@Size(max=20, message="city name too large", groups=DBChecks.class)
	@Pattern(regexp="^[a-zA-Z\\ ]+$", groups=DataChecks.class, 
	         message="city must be upper and lower case characters")
	private String city;
	
	@Column(name="STATE", length=2, nullable=false)
	@NotNull(message="state not supplied")
	@Size(min=2, max=2, message="state wrong size", groups=DBChecks.class)
	@Pattern(regexp="^[A-Z][A-Z]$", groups=DataChecks.class, 
	         message="state must be upper case letters")
	private String state;
	
	@Column(name="ZIP", length=5, nullable=false)
	@NotNull(message="zipcode not supplied")
	@Size(min=5, max=5, message="zipcode wrong size", groups=DBChecks.class)
	@Pattern(regexp="^[0-9][0-9][0-9][0-9][0-9]$", groups=DataChecks.class, 
	         message="zipcode must be numeric digits")
	private String zip;

	
	public int getId() { return id; }

	public String getStreet() { return street; }
	public Address1 setStreet(String street) {
File Project Line
ejava/examples/asyncmarket/ejb/AuctionMgmtEJB.java Async::Async Market::EJB 262
ejava/examples/asyncmarket/ejb/BuyerEJB.java Async::Async Market::EJB 136
            throw new MarketException("error removing auction items" + ex);
        }
    }
    
    private List<AuctionItem> makeDTO(List<AuctionItem> items) {
        List<AuctionItem> dto = new ArrayList<AuctionItem>();
        for (AuctionItem item : items) {
            dto.add(makeDTO(item));
        }
        return dto;
    }

    private AuctionItem makeDTO(AuctionItem item) {
        AuctionItem dto = new AuctionItem(item.getId());
        dto.setVersion(item.getVersion());
        dto.setName(item.getName());
        dto.setStartDate(item.getStartDate());
        dto.setEndDate(item.getEndDate());
        dto.setMinBid(item.getMinBid());
        dto.setBids(makeDTO(item.getBids(), dto));
        dto.setWinningBid(null);
        dto.setClosed(item.isClosed());
        return dto;
    }

    private List<Bid> makeDTO(List<Bid> bids, AuctionItem item) {
        List<Bid> dtos = new ArrayList<Bid>();
        for (Bid bid : bids) {
            Bid dto = new Bid(bid.getId());
            dto.setAmount(bid.getAmount());
            dto.setItem(item);
            item.getBids().add(dto);
            dto.setBidder(makeDTO(bid.getBidder(),dto));
            dtos.add(dto);
        }
        return dtos;
    }
File Project Line
org/myorg/jpatickets/bo/TicketPK.java EJB::JPA Tickets Lab::Exercise::Impl 5
org/myorg/jpatickets/bo/TicketPK.java EJB::JPA Tickets Lab::Solution::Impl 5
public class TicketPK implements Serializable {
    private static final long serialVersionUID = -10715122509795953L;
    private int event;
    private SeatPK seat;
    
    protected TicketPK() {}    
    public TicketPK(int event, SeatPK seat) {
        this.event = event;
        this.seat = seat;
    }

    public int getEventId() { return event; }
    public SeatPK getSeatId() { return seat; }
    
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + event;
        result = prime * result + ((seat == null) ? 0 : seat.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if (obj == null) { return false; }        
        if (getClass() != obj.getClass()) { return false; }
        TicketPK other = (TicketPK) obj;
        
        return (event != other.event) &&
            (seat == null ? other.seat == null : seat.equals(other.seat));
    }
    
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("TicketPK [event=").append(event)
            .append(", seat=").append(seat).append("]");
        return builder.toString();
    }
}
File Project Line
myorg/entityex/Auto.java JPA::Entity::Exercise Solution 13
myorg/entitymgrex/Auto.java JPA::Entity Manager::Exercise::Solution 10
myorg/relex/Auto.java JPA::Relation::Exercise Solution 13
@Entity @Table(name="EM_AUTO")
public class Auto implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    private String make;
    private String model;
    private String color;
    private int mileage;
        
    public long getId() {
        return id;
    }
    @SuppressWarnings("unused")
    private void setId(long id) {
        this.id = id;
    }
    public String getMake() {
        return make;
    }
    public void setMake(String make) {
        this.make = make;
    }
    public int getMileage() {
        return mileage;
    }
    public void setMileage(int mileage) {
        this.mileage = mileage;
    }
    public String getModel() {
        return model;
    }
    public void setModel(String model) {
        this.model = model;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder
		    .append("id=").append(id)
			.append(", make=").append(make)
			.append(", model=").append(model)
			.append(", color=").append(color)
			.append(", mileage=").append(mileage);
		return builder.toString();
	}    
}
File Project Line
myorg/queryex/MovieRolePK.java JPA::Query::Exercise::Solution 5
ejava/jpa/examples/tuning/bo/MovieRolePK.java JPA::Tuning::Example 5
public class MovieRolePK implements Serializable {
	private static final long serialVersionUID = -2134263902401216090L;
	private String movie;
	private String role;
	
	public MovieRolePK() {}
	
	public String getMovie() { return movie; }
	public MovieRolePK setMovie(String movie) {
		this.movie = movie;
		return this;
	}
	
	public String getRole() { return role; }
	public MovieRolePK setRole(String role) {
		this.role = role;
		return this;
	}

	@Override
	public int hashCode() {
		return movie==null?0:movie.hashCode() +
				role==null?0:role.hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		try {
			if (this==obj) { return true; }
			if (obj==null) { return false; }
			MovieRolePK rhs = (MovieRolePK)obj;
			if (movie!=null && role!=null) {
				return movie.equals(rhs.movie) && role.equals(rhs.role);
			}
			if (movie==null && rhs.movie!=null) { return false; }
			if (role==null && rhs.role!=null) { return false; }
			return true;
		} catch (Exception ex) { return false; }
	}
	
	@Override
	public String toString() {
		return movie + " " + role;
	}
	
}
File Project Line
org/myorg/jpatickets/dto/EventDTO.java EJB::JPA Tickets Lab::Exercise::EJB 6
org/myorg/jpatickets/dto/EventDTO.java EJB::JPA Tickets Lab::Solution::EJB 6
public class EventDTO implements Serializable {
    private static final long serialVersionUID = 4881952492348300544L;
    private int id;
    private String eventName;
    private String venueName;
    private Date startTime;
    private int numTickets;
    
    public int getId() { return id; }
    public void setId(int id) {
        this.id = id;
    }
    
    public String getEventName() { return eventName; }
    public void setEventName(String eventName) {
        this.eventName = eventName;
    }
    
    public String getVenueName() { return venueName; }
    public void setVenueName(String venueName) {
        this.venueName = venueName;
    }
    
    public Date getStartTime() { return startTime; }
    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
    
    public int getNumTickets() { return numTickets; }
    public void setNumTickets(int numTickets) {
        this.numTickets = numTickets;
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("EventDTO [id=").append(id)
            .append(", eventName=").append(eventName)
            .append(", venueName=").append(venueName)
            .append(", startTime=").append(startTime)
            .append(", numTickets=").append(numTickets)
            .append("]");
        return builder.toString();
    }
}
File Project Line
myorg/queryex/MoviePK.java JPA::Query::Exercise::Solution 6
ejava/jpa/examples/tuning/bo/MoviePK.java JPA::Tuning::Example 6
public class MoviePK implements Serializable {
	private static final long serialVersionUID = -4411388426942024278L;
	private String title;
	private Date releaseDate;

	protected MoviePK() {}
	public MoviePK(String title, Date releaseDate) {
		this.title = title;
		this.releaseDate = releaseDate;
	}
	
	public String getTitle() { return title; }
	public Date getReleaseDate() { return releaseDate; }
	
	@Override
	public int hashCode() {
		return (title==null?0:title.hashCode()) +
				(releaseDate==null?0:releaseDate.hashCode());
	}
	
	@Override
	public boolean equals(Object obj) {
		try {
			if (this == obj) { return true; }
			if (obj == null) { return false; }
			MoviePK rhs = (MoviePK)obj;
			if (title != null && releaseDate != null) {
				return title.equals(rhs.title) && releaseDate.equals(rhs.releaseDate);
			}
			if (title==null && rhs.title != null) { return false; }
			if (releaseDate==null && rhs.releaseDate != null) { return false; }
			return true;
		} catch (Exception ex) { return false; }
	}
	
}
File Project Line
myorg/queryex/Actor.java JPA::Query::Exercise::Solution 28
ejava/jpa/examples/tuning/bo/Actor.java JPA::Tuning::Example 25
	@OneToOne(optional=false, fetch=FetchType.EAGER,
			cascade={CascadeType.PERSIST, CascadeType.DETACH})
	@MapsId
	@JoinColumn(name="PERSON_ID")
	private Person person;
	
	@OneToMany(mappedBy="actor", 
			cascade={CascadeType.PERSIST, CascadeType.REMOVE})
	private Set<MovieRole> roles= new TreeSet<MovieRole>(new Comparator<MovieRole>() {
		@Override
		public int compare(MovieRole lhs, MovieRole rhs) {
			if (lhs.getMovie() != null && rhs.getMovie() != null) {
				return lhs.getMovie().compareTo(rhs.getMovie());
			}
			return 0;
		}
	});

	protected Actor() {}
	public Actor(Person person) {
		this.person = person;
	}
	
	public Person getPerson() { return person; }
	public String getFirstName() { return person==null?null : person.getFirstName(); }
	public String getLastName() { return person==null?null : person.getLastName(); }
	public Date getBirthDate() { return person==null?null : person.getBirthDate(); }
File Project Line
myorg/queryex/Movie.java JPA::Query::Exercise::Solution 13
ejava/jpa/examples/tuning/bo/Movie.java JPA::Tuning::Example 13
@Table(name="QUERYEX_MOVIE")
@NamedQueries({ 
	@NamedQuery(name="Movie.findByTitle", query=
		"select m from Movie m " +
		"where lower(m.title) like concat(concat('%',lower(:title)),'%')")
})
@SqlResultSetMappings({
	@SqlResultSetMapping(name="Movie.movieMapping", entities={
			@EntityResult(entityClass=Movie.class),
			@EntityResult(entityClass=Director.class),
			@EntityResult(entityClass=Person.class)
	}),
	@SqlResultSetMapping(name="Movie.movieMapping2", entities={
			@EntityResult(entityClass=Movie.class),
			@EntityResult(entityClass=Director.class),
			@EntityResult(entityClass=Person.class, fields={
				@FieldResult(name="id", column="p_id"),
				@FieldResult(name="firstName", column="first_name"),
				@FieldResult(name="lastName", column="last_name"),
				@FieldResult(name="birthDate", column="birth_date")
			})
	})
})
public class Movie implements Comparable<Movie>{
	@Id
	@Column(name="ID", length=36)
	private String id;
	
	@Column(name="TITLE", length=32)
File Project Line
ejava/examples/orm/core/annotated/NapsackPK.java JPA::Entity::Examples 13
ejava/examples/orm/core/mapped/NapsackPK.java JPA::Entity::Examples 12
@Embeddable
public class NapsackPK implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="NAPSACK_MAKE") //maps field to column of containing class
    private String make;
    @Column(name="NAPSACK_MODEL")//maps field to column of containing class
    private String model;
    
    public NapsackPK() {}
    public NapsackPK(String make, String model) {
        this.make = make;
        this.model = model;
    }
    
    public String getMake() { return make; }
    public void setMake(String make) {
		this.make = make;
	}
    public String getModel() { return model; }
    public void setModel(String model) {
		this.model = model;
	}

    public int hashCode() { return make.hashCode() + model.hashCode(); }
    public boolean equals(Object obj) {
        try {
            if (this == obj) return true;
            return make.equals(((NapsackPK)obj).getMake()) &&
                   model.equals(((NapsackPK)obj).getModel());
            
        } catch (Throwable ignored) { //catch NP & Cast Exceptions 
            return false;
        }
    }
    
    public String toString() {
        return new StringBuilder()
File Project Line
ejava/ejb/examples/encconfig/ejb/AnnotatedEJB.java EJB::Config Example::ENC EJB 103
ejava/ejb/examples/encconfig/ejb/XMLConfiguredEJB.java EJB::Config Example::ENC EJB 89
			jndi = new InitialContext();
			verify(jndi, "val", "value", value1, value2, value3);
			assert(value1==DEFAULT_VALUE) : "value1 value replaced";
			assert(!value2.equals(""+DEFAULT_VALUE)) : "value2 value not replaced";
			verify(jndi, "jdbc", "ds", ds1, ds2, ds3);
			verify(jndi, "jms", "queue", queue1, queue2, queue3);
			verify(jndi, "jms", "topic", topic1, topic2, topic3);
			verify(jndi, "jms", "cf", cf1, cf2, cf3);
			verify(jndi, "ejb", "ejb", ejb1, ejb2, ejb3, ejb4, ejb5, ejb6, ejb7, ejb8);
			verify(jndi, "jpa", "em", em1, em2, em3);
			verify(jndi, "jpa", "emf", emf1, emf2, emf3);
		} catch (NamingException ex) {
			throw new EJBException(ex);
		} finally {
			if (jndi!=null) {
				try { jndi.close(); }
				catch (NamingException ex) { ex.printStackTrace(); }
			}
		}
	}
}
File Project Line
ejava/examples/orm/core/annotated/Watch.java JPA::Entity::Examples 35
ejava/examples/orm/core/mapped/Watch.java JPA::Entity::Examples 17
    private String phone;

    public Watch() {}
    public Watch(long id) { this.id = id; }
    
    public long getId() { return id; }

    public String getMake() { return make; }
    public void setMake(String make) {
        this.make = make;
    }

    public String getModel() { return model; }
    public void setModel(String model) {
        this.model = model;
    }

    public String getOwner() { return owner; }
    public void setOwner(String owner) {
        this.owner = owner;
    }

    public String getCardnum() { return cardnum; }
    public void setCardnum(String cardnum) {
        this.cardnum = cardnum;
    }
    
    public String getManufacturer() { return manufacturer; }
    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getAddress() { return address; }
    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() { return phone; }
    public void setPhone(String phone) {
        this.phone = phone;
    }
File Project Line
ejava/examples/ejbwar/inventory/bo/InventoryRepresentation.java EJB::Web-oriented EJB::JAX-RS Inventory WAR 25
ejava/examples/ejbwar/customer/bo/CustomerRepresentation.java EJB::Web-oriented EJB::Customer EJB 25
	@Version
	@Column(name="VERSION")
	private int version;
	
	/**
	 * This property is added to each entity so that we can have better 
	 * control over concurrent updates
	 * @return
	 */
	@XmlAttribute(required=true)
	public int getVersion() { return version; }
	public void setVersion(int version) {
		this.version = version;
	}
	
	/**
	 * Our toString() implementation will take advantage of the JAXB defintion
	 * for the class and marshall the object as an XML string.
	 */
	@Override
	public String toString() {
		try {
			JAXBContext jbx = JAXBContext.newInstance(getClass());
			Marshaller marshaller = jbx.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			StringWriter writer = new StringWriter();
			marshaller.marshal(this, writer);
			return writer.toString();
		} catch (JAXBException ex) {
			throw new RuntimeException("unexpected JAXB error marshalling object:", ex);
		}
	}
	
	/**
	 * This method will unmarshall the specified class from the provided 
	 * XML input stream.
	 * @param clazz
	 * @param is
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T unmarshall(Class<T> clazz, InputStream is) {
		try {
			JAXBContext jbx = JAXBContext.newInstance(clazz);
			Unmarshaller marshaller = jbx.createUnmarshaller();
			return (T) marshaller.unmarshal(is);
		} catch (JAXBException ex) {
			throw new RuntimeException("unexpected JAXB error marshalling object:", ex);
		}
	}
}
File Project Line
ejava/examples/asyncmarket/web/BuyerHandlerServlet.java Async::Async Market::WAR 159
ejava/examples/asyncmarket/web/SellerHandlerServlet.java Async::Async Market::WAR 149
                  getServletContext().getRequestDispatcher(BUYERMENU_URL);
                rd.forward(request, response);                
            }
            catch (Exception ex) {
                request.setAttribute(EXCEPTION_PARAM, ex);
                RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    DISPLAY_EXCEPTION_URL);
                rd.forward(request, response);
            }
        }
    }

    private class CreateAccount extends Handler {
        public void handle(HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, IOException {
            try {
                String name = request.getParameter("name");
                String userId = request.getParameter("userId");
                
                Person user = new Person();
                user.setName(name);
                user.setUserId(userId);
                
                userMgmt.createUser(userId, name);
                user = userMgmt.getUserByUserId(userId);
                request.setAttribute(USER, user);
                
                RequestDispatcher rd = 
                  getServletContext().getRequestDispatcher(DISPLAYUSER_URL);
                rd.forward(request, response);                
            }
            catch (Exception ex) {
                request.setAttribute(EXCEPTION_PARAM, ex);
                RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    DISPLAY_EXCEPTION_URL);
                rd.forward(request, response);
            }
        }
    }
    
    private class GetAvailableItems extends Handler {
File Project Line
myorg/queryex/Director.java JPA::Query::Exercise::Solution 35
ejava/jpa/examples/tuning/bo/Director.java JPA::Tuning::Example 37
	public Director setLastName(String name) { if (person!=null){ person.setLastName(name);} return this;}
	public Director setBirthDate(Date date) { if (person!=null){ person.setBirthDate(date);} return this;}

	public Set<Movie> getMovies() {
		if (movies == null) {
			movies = new TreeSet<Movie>();
		}
		return movies;
	}
	protected void setMovies(Set<Movie> movies) {
		this.movies = movies;
	}
	public Director addMovie(Movie...movie) {
		if (movie != null) {
			for (Movie m : movie) {
				getMovies().add(m);
			}
		}
		return this;
	}
	
	@Override
	public int hashCode() {
		return (person==null ? 0 : person.hashCode());
	}
	
	@Override
	public boolean equals(Object obj) {
		try { 
			if (this==obj) { return true; }
			if (obj==null) { return false; }
			Director rhs = (Director)obj;
			if (person == null) {
				if (rhs.getPerson() != null) { return false; }
File Project Line
org/myorg/jpatickets/ejb/VenueMgmtEJB.java EJB::JPA Tickets Lab::Exercise::EJB 19
org/myorg/jpatickets/ejb/VenueMgmtEJB.java EJB::JPA Tickets Lab::Solution::EJB 21
    private static final Logger logger = LoggerFactory.getLogger(VenueMgmtEJB.class);
    
    //@PersistenceContext(unitName="jpatickets-labex")
    private EntityManager em;
    
    private VenueMgmt venueMgmt;
    
    @PostConstruct
    public void init() {
        logger.debug("*** VenueMgmtEJB:init({}) ***", super.hashCode());
        
        VenueDAOImpl vdao = new VenueDAOImpl();
        vdao.setEntityManager(em);
        venueMgmt=new VenueMgmtImpl();
        ((VenueMgmtImpl)venueMgmt).setDao(vdao);
    }
    
    @PreDestroy
    public void destroy() {
        logger.debug("*** VenueMgmtEJB:destroy({}) ***", super.hashCode()); 
    }

    @Override
    public Venue createVenue(Venue venue, int sections, int positions, int rows) {
        try {
            return venueMgmt.createVenue(venue, sections, positions, rows);
        } catch (Exception ex) {
            logger.error("error creating venue", ex);
            throw new EJBException("error creating venue:" + ex);
        }
    }

    @Override
    public Venue getVenue(String venueId) {
        try {
            return venueMgmt.getVenue(venueId);
        } catch (Exception ex) {
            logger.error("error getting venue", ex);
            throw new EJBException("error getting venue:" + ex);
        }
    }
}
File Project Line
org/myorg/jpatickets/dao/VenueDAOImpl.java EJB::JPA Tickets Lab::Exercise::Impl 12
org/myorg/jpatickets/dao/VenueDAOImpl.java EJB::JPA Tickets Lab::Solution::Impl 12
public class VenueDAOImpl implements VenueDAO {
    private EntityManager em;
    
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @Override
    public void saveVenue(Venue venue, List<Seat> seats) {
        em.setFlushMode(FlushModeType.COMMIT);
        em.persist(venue);        
        if (seats!=null) {
            for (Seat s: seats) {
                em.persist(s);
            }
        }
        em.setFlushMode(FlushModeType.AUTO);
    }
    
    public Venue getVenue(String venueId) {
        return em.find(Venue.class, venueId);
    }
    
    @Override
    public List<Seat> getSeatsForVenue(Venue venue, int offset, int limit) {
        TypedQuery<Seat> query = em.createNamedQuery("JPATicketSeat.getSeatsForVenue", 
                Seat.class)
                .setParameter("venue", venue);
        if (offset > 0) { query.setFirstResult(offset); }
        if (limit > 0) { query.setMaxResults(limit); }
        return query.getResultList();
    }
}
File Project Line
org/myorg/jpatickets/webejb/WebVenueMgmtEJB.java EJB::JPA Tickets Lab::Exercise::WAR 23
org/myorg/jpatickets/webejb/WebVenueMgmtEJB.java EJB::JPA Tickets Lab::Solution::WAR 23
    @PersistenceContext(unitName="jpaticketsweb-labex")
    private EntityManager em;
    
    private VenueMgmt venueMgmt;
    
    @PostConstruct
    public void init() {
        logger.debug("*** WebVenueMgmtEJB:init({}) ***", super.hashCode());
        
        VenueDAOImpl vdao = new VenueDAOImpl();
        vdao.setEntityManager(em);
        venueMgmt=new VenueMgmtImpl();
        ((VenueMgmtImpl)venueMgmt).setDao(vdao);
    }
    
    @PreDestroy
    public void destroy() {
        logger.debug("*** WebVenueMgmtEJB:destroy({}) ***", super.hashCode()); 
    }

    @Override
    public Venue createVenue(Venue venue, int sections, int positions, int rows) {
        try {
            return venueMgmt.createVenue(venue, sections, positions, rows);
        } catch (Exception ex) {
            logger.error("error creating venue", ex);
            throw new EJBException("error creating venue:" + ex);
        }
    }

    @Override
    public Venue getVenue(String venueId) {
        try {
            return venueMgmt.getVenue(venueId);
        } catch (Exception ex) {
            logger.error("error getting venue", ex);
            throw new EJBException("error getting venue:" + ex);
        }
    }
}
File Project Line
myorg/queryex/Movie.java JPA::Query::Exercise::Solution 181
ejava/jpa/examples/tuning/bo/Movie.java JPA::Tuning::Example 203
		if (minutes != rhs.minutes) {
			return false; 
		} 
		
		if (rating == null) {
			if (rhs.rating != null) { return false; }
		} else if (!rating.equals(rhs.rating)) {
			return false;
		}
		
		return true;			
	}
	
	@Override
	public int compareTo(Movie rhs) {
		if (rhs == null) { return 1; }
		
		if (title != null && rhs.title != null && title.compareTo(rhs.title)!=0) {
			return title.compareTo(rhs.title);
		}
		if (releaseDate != null && rhs.releaseDate != null && releaseDate.compareTo(rhs.releaseDate)!=0) {
			return releaseDate.compareTo(rhs.releaseDate);
		}
		return 0;
	}
	
	@Override
	public String toString() {
		DateFormat df = new SimpleDateFormat("yyyy");
		return title + (releaseDate==null ? "" : " (" + df.format(releaseDate) + ")"); 
	}
}
File Project Line
org/myorg/encconfig/bo/AuditRecord.java EJB::ENC Config Lab::Exercise:EJB 15
org/myorg/encconfig/bo/AuditRecord.java EJB::ENC Config Lab::Solution::EJB 15
@Entity
@Table(name="EJBCONFIG_AUDITREC")
public class AuditRecord {
	@Id @GeneratedValue
	private int id;
	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable=false)
	private Date timestamp;
	@Column(length=200, nullable=false)
	private String message;
	
	protected AuditRecord(){}
	public AuditRecord(Date timestamp, String message) {
		this.timestamp = timestamp;
		this.message = message;
	}
	
	public int getId() { return id; }
	public Date getTimestamp() { return timestamp; }
	public void setTimestamp(Date timestamp) {
		this.timestamp = timestamp;
	}
	
	public String getMessage() { return message; }
	public void setMessage(String message) {
		this.message = message;
	}
	
	@Override
	public String toString() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
		return (timestamp==null?null : df.format(timestamp)) + 
				", " + message;
	}
}
File Project Line
org/myorg/jpatickets/bl/VenueMgmtImpl.java EJB::JPA Tickets Lab::Exercise::Impl 11
org/myorg/jpatickets/bl/VenueMgmtImpl.java EJB::JPA Tickets Lab::Solution::Impl 11
public class VenueMgmtImpl implements VenueMgmt {
    VenueDAO dao;
    
    public void setDao(VenueDAO dao) {
        this.dao = dao;
    }

    @Override
    public Venue createVenue(Venue venue, int sections, int positions, int rows) {
        List<Seat> seats = new ArrayList<Seat>(sections * positions * rows);
        for (int s=0; s<sections; s++) {
            String section = Character.toString((char)('A'+s));
            for (int row=0; row<rows; row++) {
                for (int pos=0; pos<positions; pos++) {
                    Seat seat = new Seat(venue, section, row, pos);
                    seats.add(seat);
                }
            }
        }
        dao.saveVenue(venue, seats);
        return venue;
    }

    @Override
    public Venue getVenue(String venueId) {
        return dao.getVenue(venueId);
    }
}
File Project Line
ejava/examples/asyncmarket/ejb/AuctionMgmtEJB.java Async::Async Market::EJB 215
ejava/examples/asyncmarket/ejb/SellerEJB.java Async::Async Market::EJB 131
            message.setJMSType("saleUpdate");
            message.setLong("id", item.getId());
            message.setString("name", item.getName());
            message.setString("seller", item.getOwner().getUserId());
            message.setLong("startDate", item.getStartDate().getTime());
            message.setLong("endDate", item.getEndDate().getTime());
            message.setDouble("minBid", item.getMinBid());
            message.setDouble("bids", item.getBids().size());
            message.setDouble("highestBid", 
                    (item.getHighestBid() == null ? 0.00 :
                        item.getHighestBid().getAmount()));            
            producer.send(message);
            log.debug("sent=" + message);
        }
        finally {
            if (producer != null)   { producer.close(); }
        }
    }

    
    public void removeBid(long bidId) throws MarketException {
File Project Line
ejava/examples/jmsnotifier/Publisher.java Async::JMS (Topic) Notifier 138
ejava/examples/jmsscheduler/Requestor.java Async::JMS (Queue) Scheduler 202
                    destinationJNDI=args[++i];
                }
                else if ("-name".equals(args[i])) {
                    name=args[++i];
                }
                else if ("-sleep".equals(args[i])) {
                    sleepTime=new Long(args[++i]);
                }
                else if ("-max".equals(args[i])) {
                    maxCount=new Integer(args[++i]);
                }
                else if ("-username".equals(args[i])) {
                	username=args[++i];
                }
                else if ("-password".equals(args[i])) {
                	password=args[++i];
                }
                else if ("-noExit".equals(args[i])) {
                	noExit=true;
                }
            }
            if (connFactoryJNDI==null) { 
                throw new Exception("jndi.name.connFactory not supplied");
            }
            else if (destinationJNDI==null) {
File Project Line
myorg/queryex/Actor.java JPA::Query::Exercise::Solution 58
ejava/jpa/examples/tuning/bo/Actor.java JPA::Tuning::Example 56
	public int getVersion() { return version; }

	public Set<MovieRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<MovieRole> roles) {
		this.roles = roles;
	}
	
	@Override
	public int hashCode() {
		return (person==null ? 0 : person.hashCode());
	}
	
	@Override
	public boolean equals(Object obj) {
		try { 
			if (this==obj) { return true; }
			if (obj==null) { return false; }
			Actor rhs = (Actor)obj;
			if (person == null) {
				if (rhs.person != null) { return false; }
			} else if (!person.equals(rhs.person)) {
				return false;
			}
			return true;
		} catch (Exception ex) { return false; }
	}
	
	@Override
	public String toString() {
		return person.toString() + ", version=" + version; 
File Project Line
ejava/examples/asyncmarket/web/AuctionAdminHandlerServlet.java Async::Async Market::WAR 88
ejava/examples/asyncmarket/web/BuyerHandlerServlet.java Async::Async Market::WAR 97
ejava/examples/asyncmarket/web/SellerHandlerServlet.java Async::Async Market::WAR 93
                    handler.handle(request, response);
                }
                else {
                    request.setAttribute("handlers", handlers);
                    RequestDispatcher rd = 
                        getServletContext().getRequestDispatcher(
                            UNKNOWN_COMMAND_URL);
                            rd.forward(request, response);
                }
            }
            else {
                throw new Exception("no " + COMMAND_PARAM + " supplied"); 
            }
        }
        catch (Exception ex) {
            request.setAttribute(EXCEPTION_PARAM, ex);
            RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    UNKNOWN_COMMAND_URL);
                    rd.forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response) 
        throws ServletException, IOException {
        log.debug("doPost() called, calling doGet()");
        doGet(request, response);
    }

    public void destroy() {
        log.debug("destroy() called");
    }
    
    private abstract class Handler {
        protected static final String RESULT_PARAM = "result";
        protected static final String MAINMENU_URL = 
            "/index.jsp";
        protected static final String ADMINMENU_URL = 
File Project Line
org/myorg/jpatickets/bo/Event.java EJB::JPA Tickets Lab::Exercise::Impl 10
org/myorg/jpatickets/bo/Event.java EJB::JPA Tickets Lab::Solution::Impl 10
@SuppressWarnings("serial")
@Entity
@Table(name="JPATICKETS_EVENT")
@NamedQueries({
    @NamedQuery(name="JPATicketEvent.fetchEventTickets", 
        query="select e from Event e "
                + "join fetch e.tickets "
                + "where e.id=:eventId"),
    @NamedQuery(name="JPATicketEvent.fetchEventTicketsSeats", 
        query="select e from Event e "
                + "join fetch e.venue "
                + "join fetch e.tickets t "
                + "join fetch t.seat "
                + "where e.id=:eventId")
})
@NamedNativeQueries({
    @NamedNativeQuery(name="JPATicketEvent.fetchEventDTO",
            query="select event.EVENT_ID, event.EVENT_NAME, event.START_TIME, event.VENUE_ID, "
                    + "venue.NAME venueName, count(ticket.*) numTickets "
                    + "from JPATICKETS_EVENT event "
                    + "join JPATICKETS_VENUE venue on venue.VENUE_ID = event.VENUE_ID "
                    + "join JPATICKETS_TICKET ticket on ticket.EVENT_ID = event.EVENT_ID "
                    + "where event.EVENT_ID = :eventId "
                    + "group by event.EVENT_ID, event.EVENT_NAME, event.START_TIME, event.VENUE_ID, venue.NAME",
            resultSetMapping="JPATicketEvent.EventDTOMapping")
})
@SqlResultSetMappings({
    @SqlResultSetMapping(name="JPATicketEvent.EventDTOMapping",
            entities={
                @EntityResult(entityClass=Event.class)
                },
            columns={
                @ColumnResult(name="venueName", type=String.class),
                @ColumnResult(name="numTickets", type=Long.class)
                }
    )
})
public class Event /* implements Serializable */ {
File Project Line
org/myorg/encconfig/ejb/XMLInjectAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 10
org/myorg/encconfig/ejb/XMLInjectAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 12
public class XMLInjectAuditorEJB extends AuditorBase 
	implements AuditorRemote {
	private static final Logger log = LoggerFactory.getLogger(XMLInjectAuditorEJB.class);
	
	private Boolean publishJMS;
	private EntityManager em;
	private ConnectionFactory cf;
	private Topic topic;
	
	public void init() {
		super.setLog(log);
		super.setConnectionFactory(cf);
		super.setEntityManager(em);
		super.setTopic(topic);
		super.setPublishJMS(isPublishJMS());
	}

	@Override
	public boolean isPublishJMS() {
		return publishJMS!=null && publishJMS;
	}
	@Override
	public boolean havePersistenceContext() {
		return em!=null;
	}
	@Override
	public boolean haveTopic() {
		return topic!=null;
	}
	@Override
	public boolean haveConnectionFactory() {
		return cf!=null;
	}	
	@Override
	public int audit(String message) {
		return super.audit(message);
	}
}
File Project Line
ejava/examples/orm/core/annotated/MakeModelPK.java JPA::Entity::Examples 14
ejava/examples/orm/core/mapped/MakeModelPK.java JPA::Entity::Examples 14
@Embeddable
public class MakeModelPK implements Serializable {
    private static final long serialVersionUID = 1L;
    private String make;
    private String model;
    
    public MakeModelPK() {}
    public MakeModelPK(String make, String model) {
        this.make = make;
        this.model = model;
    }
    
    public String getMake() { return make; }
    public String getModel() { return model; }

    public int hashCode() { return make.hashCode() + model.hashCode(); }
    public boolean equals(Object obj) {
        try {
            if (this == obj) return true;
            return make.equals(((MakeModelPK)obj).getMake()) &&
                   model.equals(((MakeModelPK)obj).getModel());
            
        } catch (Throwable ignored) { //catch NP & Cast Exceptions 
            return false;
        }
    }
File Project Line
ejava/examples/orm/core/annotated/Vase.java JPA::Entity::Examples 27
ejava/examples/orm/core/mapped/Vase.java JPA::Entity::Examples 17
    private ColorType colorName;

    public Vase() {}
    public Vase(long id) { this.id = id; }

    public long getId() { return id; }
    
    public Date getADate() { return aDate; }
    public void setADate(Date date) {
        aDate = date;
    }
    
    public Date getATime() { return aTime; }
    public void setATime(Date time) {
        aTime = time;
    }
    
    public Date getATimestamp() { return aTimestamp; }
    public void setATimestamp(Date timestamp) {
        aTimestamp = timestamp;
    }
    
    public ColorType getColorId() { return colorId; }
    public void setColorId(ColorType colorId) {
        this.colorId = colorId;
    }

    public ColorType getColorName() { return colorName; }
    public void setColorName(ColorType colorName) {
        this.colorName = colorName;
    }
File Project Line
myorg/queryex/Movie.java JPA::Query::Exercise::Solution 120
ejava/jpa/examples/tuning/bo/Movie.java JPA::Tuning::Example 141
		return this;
	}
	

	public Director getDirector() { return director; }
	public Movie setDirector(Director director) {
		this.director = director;
		return this;
	}

	public Set<MovieRole> getCast() {
		if (cast==null) {
			cast=new HashSet<MovieRole>();
		}
		return cast; 
	}
	protected void setCast(Set<MovieRole> cast) {
		this.cast = cast;
	}
	public Movie addRole(MovieRole...role) {
		if (role!=null) { 
			for (MovieRole r : role) {
				r.setMovie(this);
				getCast().add(r);
			}
		}
		return this;
	}
	@Override
	public int hashCode() {
		return (director== null ? 0 : director.hashCode()) +
File Project Line
myorg/queryex/Director.java JPA::Query::Exercise::Solution 10
ejava/jpa/examples/tuning/bo/Director.java JPA::Tuning::Example 10
@Table(name="QUERYEX_DIRECTOR")
public class Director {
	@Id
	private String id;
	
	@OneToOne(optional=false, fetch=FetchType.EAGER,
			cascade={CascadeType.PERSIST, CascadeType.DETACH})
	@JoinColumn(name="PERSON_ID")
	@MapsId
	private Person person;

	@OneToMany(mappedBy="director", 
			cascade={CascadeType.PERSIST, CascadeType.DETACH})	
	private Set<Movie> movies;

	protected Director() {}	
	public Director(Person person) {
		this.person = person;
	}

	public Person getPerson() { return person; }
	public String getFirstName() { return person==null?null : person.getFirstName(); }
	public String getLastName() { return person==null?null : person.getLastName(); }
	public Date getBirthDate() { return person==null?null : person.getBirthDate(); }
File Project Line
org/myorg/encconfig/ejb/JNDIAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 33
org/myorg/encconfig/ejb/JNDIAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 36
			jndi=new InitialContext();
			//TODO enc-config 19: lookup resource value in ENC 
			//publishJMS = (Boolean) ctx.lookup("val/publishJMS");
			//TODO enc-config 20: lookup persistence context in ENC 
			//em = (EntityManager) ctx.lookup("jpa/em");
			//TODO enc-config 21: lookup resource in ENC using JNDI java:comp/env 
			//topic = (Topic) jndi.lookup("java:comp/env/jms/topic");
			//TODO enc-config 22: lookup resource in ENC using JNDI java:comp/env
			//cf = (ConnectionFactory) jndi.lookup("java:comp/env/jms/cf");
		} catch (NamingException ex) {
			log.error("error looking up resources", ex);
			throw new EJBException("error looking up resources:" + ex);
		} finally {
			close(jndi);
		}
		super.setLog(log);
		super.setConnectionFactory(cf);
		super.setEntityManager(em);
		super.setTopic(topic);
		super.setPublishJMS(isPublishJMS());
	}

	@Override
	public boolean isPublishJMS() {
		return publishJMS!=null && publishJMS;
	}
	@Override
	public boolean havePersistenceContext() {
		return em!=null;
	}
	@Override
	public boolean haveTopic() {
		return topic!=null;
	}
	@Override
	public boolean haveConnectionFactory() {
		return cf!=null;
	}
	
	@Override
	public int audit(String message) {
		return super.audit(message);
	}
}
File Project Line
ejava/examples/asyncmarket/web/AuctionAdminHandlerServlet.java Async::Async Market::WAR 204
ejava/examples/asyncmarket/web/BuyerHandlerServlet.java Async::Async Market::WAR 288
ejava/examples/asyncmarket/web/SellerHandlerServlet.java Async::Async Market::WAR 242
                  getServletContext().getRequestDispatcher(ADMINMENU_URL);
                rd.forward(request, response);                
            }
            catch (Exception ex) {
                request.setAttribute(EXCEPTION_PARAM, ex);
                RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    DISPLAY_EXCEPTION_URL);
                rd.forward(request, response);
            }
        }
    }

    private class Logout extends Handler {
        public void handle(HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, IOException {
            try {
                request.getSession().invalidate();
                
                RequestDispatcher rd = 
                  getServletContext().getRequestDispatcher(MAINMENU_URL);
                rd.forward(request, response);                
            }
            catch (Exception ex) {
                request.setAttribute(EXCEPTION_PARAM, ex);
                RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    DISPLAY_EXCEPTION_URL);
                rd.forward(request, response);
            }
        }
    }
}
File Project Line
ejava/examples/orm/core/annotated/Pen.java JPA::Entity::Examples 11
ejava/examples/orm/core/mapped/Pen.java JPA::Entity::Examples 11
@Entity
@Table(name="ORMCORE_PEN")
public class Pen {
    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(name="make", column=@Column(name="PEN_MAKE")),
        @AttributeOverride(name="model", column=@Column(name="PEN_MODEL"))             
        })
    private MakeModelPK pk;
    private int size;
    
    public Pen() {}
    public Pen(String make, String model) {
        this.pk = new MakeModelPK(make, model);
    }
    
    public MakeModelPK getPk() { return pk; }
    
    public int getSize() { return size; }
    public void setSize(int size) {
        this.size = size;
    }
    
    public String toString() {
        return new StringBuilder()
File Project Line
myorg/queryex/Movie.java JPA::Query::Exercise::Solution 151
ejava/jpa/examples/tuning/bo/Movie.java JPA::Tuning::Example 171
				minutes +
				(rating==null? 0 : rating.hashCode()) +
				(releaseDate==null? 0 : releaseDate.hashCode()) +
				(title==null ? 0 : title.hashCode());
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj) { return true; }
		if (obj == null) { return false; }
		Movie rhs = (Movie)obj;
		
		if (title==null) {
			if (rhs.title != null) { return false; }
		} else if (!title.equals(rhs.title)) {
			return false;
		}
		
		if (director==null) {
			if (rhs.getDirector() != null) { return false; }
File Project Line
org/myorg/encconfig/ejb/ENCAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 17
org/myorg/encconfig/ejb/LookupAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 18
	private static final Logger log = LoggerFactory.getLogger(ENCAuditorEJB.class);
	//TODO: enc-config 12: define a resource value ENC injection
	//@Resource(name="val/publishJMS")
	private Boolean publishJMS;
	
	//TODO: enc-config 13: define a persistence context ENC injection
	//@PersistenceContext(name="jpa/em")
	private EntityManager em;
	
	//TODO: enc-config 14: define a resource-env ENC injection
	//@Resource(name="jms/topic")
	private Topic topic;

	//TODO: enc-config 15: define a resource ENC injection
	//@Resource(name="jms/cf")
	private ConnectionFactory cf;
	
	//TODO: enc-config 16: activate this method after injection
	//@PostConstruct
	public void init() {
		super.setLog(log);
		super.setConnectionFactory(cf);
		super.setEntityManager(em);
		super.setTopic(topic);
		super.setPublishJMS(isPublishJMS());
	}	
	
	@Override
	public boolean isPublishJMS() {
		return publishJMS!=null && publishJMS;
	}
	@Override
	public boolean havePersistenceContext() {
		return em!=null;
	}
	@Override
	public boolean haveTopic() {
		return topic!=null;
	}
	@Override
	public boolean haveConnectionFactory() {
		return cf!=null;
	}
	
	@Override
	public int audit(String message) {
		return super.audit(message);
	}
}
File Project Line
ejava/examples/asyncmarket/web/AuctionAdminHandlerServlet.java Async::Async Market::WAR 63
ejava/examples/asyncmarket/web/BuyerHandlerServlet.java Async::Async Market::WAR 71
ejava/examples/asyncmarket/web/SellerHandlerServlet.java Async::Async Market::WAR 65
                auctionMgmt = jndi.getAuctionMgmt();
            }        
            if (userMgmt == null) {
                userMgmt = jndi.getUserMgmt();
            }        
        }
        catch (Exception ex) {
            log.fatal("error initializing handler", ex);
            throw new ServletException("error initializing handler", ex);
        }
        finally {
        	if (jndi != null) { jndi.close(); }
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) 
        throws ServletException, IOException {
        log.debug("doGet() called");
        String command = request.getParameter(COMMAND_PARAM);
        log.debug("command=" + command);
        try {            
            if (command != null) {
                Handler handler = handlers.get(command);
                if (handler != null) {
File Project Line
ejava/examples/orm/core/annotated/Manufacturer.java JPA::Entity::Examples 12
ejava/examples/orm/core/mapped/Manufacturer.java JPA::Entity::Examples 12
    private String name;
    private String address;
    private String phone;
    
    public Manufacturer() {}
    public Manufacturer(String name, String address, String phone) {
        this.name = name;
        this.address = address;
        this.phone=phone;
    }
    
    public String getAddress() { return address; }
    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() { return name; }
    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() { return phone; }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    public String toString() {
        return new StringBuilder()
File Project Line
myorg/entityex/annotated/Animal2.java JPA::Entity::Exercise Solution 14
myorg/entityex/mapped/Animal.java JPA::Entity::Exercise Solution 13
	public Animal2(String name, Date dob, double weight) {
		this.name = name;
		this.dob = dob;
		this.weight = weight;
	}
	
	public int getId() { return id; }
	public void setId(int id) {
		this.id = id;
	}
	
	public String getName() { return name; }
	public void setName(String name) {
		this.name = name;
	}
	
	public Date getDob() { return dob; }
	public void setDob(Date dob) {
		this.dob = dob;
	}
	
	public double getWeight() { return weight; }
	public void setWeight(double weight) {
		this.weight = weight;
	}
File Project Line
org/myorg/encconfig/ejb/ENCAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 27
org/myorg/encconfig/ejb/LookupAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 27
	@Resource(name="jms/topic")
	private Topic topic;

	@PostConstruct
	public void init() {
		super.setLog(log);
		super.setConnectionFactory(cf);
		super.setEntityManager(em);
		super.setTopic(topic);
		super.setPublishJMS(isPublishJMS());
	}	
	
	@Override
	public boolean isPublishJMS() {
		return publishJMS!=null && publishJMS;
	}
	@Override
	public boolean havePersistenceContext() {
		return em!=null;
	}
	@Override
	public boolean haveTopic() {
		return topic!=null;
	}
	@Override
	public boolean haveConnectionFactory() {
		return cf!=null;
	}
	
	@Override
	public int audit(String message) {
		return super.audit(message);
	}
}
File Project Line
org/myorg/encconfig/ejb/ENCAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 36
org/myorg/encconfig/ejb/LookupAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 37
org/myorg/encconfig/ejb/XMLInjectAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 19
org/myorg/encconfig/ejb/ENCAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 31
org/myorg/encconfig/ejb/LookupAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 31
org/myorg/encconfig/ejb/XMLInjectAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 21
	public void init() {
		super.setLog(log);
		super.setConnectionFactory(cf);
		super.setEntityManager(em);
		super.setTopic(topic);
		super.setPublishJMS(isPublishJMS());
	}	
	
	@Override
	public boolean isPublishJMS() {
		return publishJMS!=null && publishJMS;
	}
	@Override
	public boolean havePersistenceContext() {
		return em!=null;
	}
	@Override
	public boolean haveTopic() {
		return topic!=null;
	}
	@Override
	public boolean haveConnectionFactory() {
		return cf!=null;
	}
	
	@Override
	public int audit(String message) {
		return super.audit(message);
	}
}
File Project Line
org/myorg/jpatickets/ejb/VenueMgmtEJB.java EJB::JPA Tickets Lab::Exercise::EJB 38
org/myorg/jpatickets/webejb/WebVenueMgmtEJB.java EJB::JPA Tickets Lab::Exercise::WAR 40
org/myorg/jpatickets/ejb/VenueMgmtEJB.java EJB::JPA Tickets Lab::Solution::EJB 38
org/myorg/jpatickets/webejb/WebVenueMgmtEJB.java EJB::JPA Tickets Lab::Solution::WAR 40
        logger.debug("*** VenueMgmtEJB:destroy({}) ***", super.hashCode()); 
    }

    @Override
    public Venue createVenue(Venue venue, int sections, int positions, int rows) {
        try {
            return venueMgmt.createVenue(venue, sections, positions, rows);
        } catch (Exception ex) {
            logger.error("error creating venue", ex);
            throw new EJBException("error creating venue:" + ex);
        }
    }

    @Override
    public Venue getVenue(String venueId) {
        try {
            return venueMgmt.getVenue(venueId);
        } catch (Exception ex) {
            logger.error("error getting venue", ex);
            throw new EJBException("error getting venue:" + ex);
        }
    }
}
File Project Line
ejava/examples/orm/core/annotated/Bike.java JPA::Entity::Examples 16
ejava/examples/orm/core/mapped/Bike.java JPA::Entity::Examples 9
    private long id;
    private String make;
    private String model;
    private int size;
    
    public Bike() {} //required non-private default ctor
    public Bike(long id) { this.id = id; }

    public long getId() { return id; }

    public String getMake() { return make; }
    public void setMake(String make) {
        this.make = make;
    }
    
    public String getModel() { return model; }
    public void setModel(String model) {
        this.model = model;
    }
    
    public int getSize() { return size; }
    public void setSize(int size) {
        this.size = size;
    }
File Project Line
info/ejava/examples/ejb/basic/ejb/GreeterEJB.java EJB::Basic EJB::EJB 27
info/ejava/examples/ejb/basic/webejb/WebGreeterEJB.java EJB::Basic EJB::WAR 23
        logger.info("*** GreeterEJB:destroy({}) ***", super.hashCode());
    }
    
    /**
     * This method is an example of a business method that can be invoked by
     * users of this object (if a POJO) or bean (if deployed as an EJB).
     */
    @Override
    public String sayHello(String name) throws BadRequestException {
        logger.debug("sayHello({})", name);

        if (name == null || name.isEmpty()) {
            throw new BadRequestException(
                    "you must have a name for me to say hello");
        }
        return "hello " + name;
    }

    /**
     * This method is an example of a business method that
     */
    @Override
    public Greeting sayHello(Name name) throws BadRequestException {
        logger.debug("sayHello({})", name);

        if (name == null) {
            throw new BadRequestException(
                    "you must have a name for me to say hello");
        }
        return new Greeting(new Date(), 
                "hello " + name.getFirstName() + " " + name.getLastName());
    }
}
File Project Line
ejava/examples/orm/core/annotated/Mower.java JPA::Entity::Examples 12
ejava/examples/orm/core/mapped/Mower.java JPA::Entity::Examples 15
@Entity
@Table(name="ORMCORE_MOWER")
@IdClass(MowerPK.class)
public class Mower {
    @Id
    private String make;
    @Id
    private String model;    
    private int size;
    
    public Mower() {}
    public Mower(String make, String model) {
        this.make = make;
        this.model = model;
    }
    
    public String getMake() { return make; }    
    public String getModel() { return model; }

    public int getSize() { return size; }
    public void setSize(int size) {
        this.size = size;
    }
    
    public String toString() {
        return new StringBuilder()
File Project Line
ejava/examples/jmsnotifier/Subscriber.java Async::JMS (Topic) Notifier 128
ejava/examples/jmsscheduler/Worker.java Async::JMS (Queue) Scheduler 150
            log.info("subscriber " + name + " stopping");
            connection.stop();
        }
        finally {
            stopped = true;
            started = false;
            if (consumer != null)   { consumer.close(); }
            if (session!=null){ session.close();}
            if (connection != null) { connection.close(); }
        }
    }
    
    public void run() {
        try {
            execute();
        }
        catch (Exception ex) {
            log.fatal("error running " + name, ex);
        }
    }    

    public static void main(String args[]) {
    	boolean noExit=false;
        try {
File Project Line
org/myorg/encconfig/ejb/ENCAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 37
org/myorg/encconfig/ejb/JNDIAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 48
org/myorg/encconfig/ejb/LookupAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 38
org/myorg/encconfig/ejb/XMLInjectAuditorEJB.java EJB::ENC Config Lab::Exercise:EJB 20
org/myorg/encconfig/ejb/ENCAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 32
org/myorg/encconfig/ejb/JNDIAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 43
org/myorg/encconfig/ejb/LookupAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 32
org/myorg/encconfig/ejb/XMLInjectAuditorEJB.java EJB::ENC Config Lab::Solution::EJB 22
		super.setLog(log);
		super.setConnectionFactory(cf);
		super.setEntityManager(em);
		super.setTopic(topic);
		super.setPublishJMS(isPublishJMS());
	}	
	
	@Override
	public boolean isPublishJMS() {
		return publishJMS!=null && publishJMS;
	}
	@Override
	public boolean havePersistenceContext() {
		return em!=null;
	}
	@Override
	public boolean haveTopic() {
		return topic!=null;
	}
	@Override
	public boolean haveConnectionFactory() {
		return cf!=null;
	}
	
	@Override
	public int audit(String message) {
		return super.audit(message);
	}
}
File Project Line
ejava/examples/webtier/bo/Person.java Web-Tier::Business Objects 25
ejava/examples/orm/ejbql/annotated/Customer.java JPA::Query::Legacy Examples/Slides 24
    private void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String toString() {
        StringBuilder text = new StringBuilder();
        text.append("id=" + id);
        text.append(", firstName=" + firstName);
        text.append(", lastName=" + lastName);
        return text.toString();
    }
}
File Project Line
ejava/examples/asyncmarket/ejb/AuctionMgmtEJB.java Async::Async Market::EJB 215
ejava/examples/asyncmarket/ejb/SellerEJB.java Async::Async Market::EJB 131
ejava/examples/asyncmarket/ejb/SellerEJB.java Async::Async Market::EJB 261
            message.setJMSType("saleUpdate");
            message.setLong("id", item.getId());
            message.setString("name", item.getName());
            message.setString("seller", item.getOwner().getUserId());
            message.setLong("startDate", item.getStartDate().getTime());
            message.setLong("endDate", item.getEndDate().getTime());
            message.setDouble("minBid", item.getMinBid());
            message.setDouble("bids", item.getBids().size());
            message.setDouble("highestBid", 
File Project Line
ejava/examples/ejbwar/inventory/client/InventoryClientImpl.java EJB::Web-oriented EJB::JAX-RS Inventory WAR 81
ejava/examples/ejbwar/inventory/client/InventoryClientImpl.java EJB::Web-oriented EJB::JAX-RS Inventory WAR 180
		URI uri = buildURI(CategoriesResource.class,"findCategoriesByName")
				//marshall @QueryParams into URI
				.queryParam("name", name)
				.queryParam("offset", offset)
				.queryParam("limit", limit)
				.build();
		
		//build the overall request 
		HttpGet get = new HttpGet(uri);
		get.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);
		
		//issue request and look for an OK response with entity
		HttpResponse response = client.execute(get);
		log.info(String.format("%s %s", get.getURI(), response));
		if (Response.Status.OK.getStatusCode() == response.getStatusLine().getStatusCode()) {
			return InventoryRepresentation.unmarshall(Categories.class,
File Project Line
org/myorg/jpatickets/ejb/TicketsInitEJB.java EJB::JPA Tickets Lab::Exercise::EJB 20
org/myorg/jpatickets/ejb/TicketsInitEJB.java EJB::JPA Tickets Lab::Solution::EJB 20
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@AccessTimeout(value=3, unit=TimeUnit.SECONDS)
public class TicketsInitEJB implements TicketsInitRemote {
    private static final Logger logger = LoggerFactory.getLogger(TicketsInitEJB.class);
    
    @EJB
    private TicketsInitTxEJB txHelper;
    
    @PostConstruct
    public void init() {
        resetDB();
    }
    
    @Override
    @Lock(LockType.WRITE)
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void resetDB() {
        logger.info("*** resetDB ***");
        //execute the following in separate transactions
        txHelper.dropDB();
        txHelper.createDB();
    }
    
}
File Project Line
info/ejava/examples/secureping/ejb/SecurePingEJB.java EJB::Security::Secure Ping::EJB 38
info/ejava/examples/secureping/ejb/SecurePingClientEJB.java EJB::Security::Secure Ping Client::EJB 44
        text.append("called " + prefix);
        try {
            text.append(", principal=" + ctx.getCallerPrincipal().getName());
            text.append(", isUser=" + ctx.isCallerInRole("user"));
            text.append(", isAdmin=" + ctx.isCallerInRole("admin"));
            text.append(", isInternalRole=" + 
                    ctx.isCallerInRole("internalRole"));
        }
        catch (Throwable ex) {
            logger.debug("error calling session context:", ex);
            text.append(", error calling Session Context:" + ex);
        }
        String result = text.toString();
        logger.debug(result);
        return result;        
    }
File Project Line
ejava/examples/orm/rel/annotated/Author.java JPA::Relation::Examples 33
ejava/examples/orm/rel/annotated/Inventory.java JPA::Relation::Examples 32
    public void setMedia(List<Media> media) {
        this.media = media;
    }

    public String getName() { return name; }
    public void setName(String name) {
        this.name = name;
    }
    
    public String toString() {
        StringBuilder text = new StringBuilder(super.toString());
        text.append(", id=" + id);
        text.append(", name=" + name);
        text.append(", media(" + media.size() + ")={");
        for (Media m: media) {
            text.append(m.getId() + ", ");
File Project Line
ejava/examples/jmsscheduler/Requestor.java Async::JMS (Queue) Scheduler 211
ejava/examples/jmsscheduler/Worker.java Async::JMS (Queue) Scheduler 204
                    maxCount=new Integer(args[++i]);
                }
                else if ("-username".equals(args[i])) {
                    username=args[++i];
                }
                else if ("-password".equals(args[i])) {
                    password=args[++i];
                }
                else if ("-noExit".equals(args[i])) {
                    noExit=true;
                }
            }
            if (connFactoryJNDI==null) { 
                throw new Exception("jndi.name.connFactory not supplied");
            }
            else if (requestQueueJNDI==null) {
                throw new Exception("jndi.name.requestQueue not supplied");
            }