package org.laughingpanda.ejb_migration_example.ejb; import org.laughingpanda.ejb_migration_example.*; import javax.ejb.*; import javax.sql.DataSource; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Collection; import java.rmi.RemoteException; /** * @author Timo Rantalaiho */ public class PersonManagerBean implements SessionBean, PersonFinder { private ServiceLocator serviceLocator = new ServiceLocatorImpl(); public void setSessionContext(SessionContext sessionContext) throws EJBException { } public void ejbCreate() throws EJBException { } public void ejbRemove() throws EJBException { } public void ejbActivate() throws EJBException { } public void ejbPassivate() throws EJBException { } public List findPersons(SearchParameters searchParameters) { PersonEntityHome home = serviceLocator.getPersonEntityHome(); try { Collection rawResults = home.findBySearchTerm(searchParameters.getSearchTerm() + "%"); List results = new ArrayList(rawResults.size()); for (Object o : rawResults) { results.add((Person) o); } return results; } catch (Exception e) { throw new RuntimeException(e); } } public PersonEntity create(String userName, String firstName, String lastName) throws CreateException { Long newId; try { newId = doSearch("SELECT MAX(id) + 1 FROM personEntity").iterator().next(); } catch (SQLException e) { throw new RuntimeException(e); } PersonEntityHome home = serviceLocator.getPersonEntityHome(); try { return home.create(newId, userName, firstName, lastName); } catch (RemoteException e) { throw new RuntimeException(e); } } private List doSearch(String sql) throws SQLException { List results = new ArrayList(); DataSource dataSource = new ServiceLocatorImpl().getDataSource(); Connection connection = dataSource.getConnection(); PreparedStatement statement = null; try { statement = connection.prepareStatement(sql); ResultSet rs = statement.executeQuery(); while (rs.next()) { results.add(rs.getLong(1)); } } finally { cleanUp(connection, statement); } return results; } private void cleanUp(Connection connection, Statement statement) throws SQLException { if (statement != null) { try { statement.close(); } finally { connection.close(); } } } }