Project Student: Business Layer

This is part of Project Student. Other posts are Webservice Client With Jersey, Webservice Server with Jersey and Persistence with Spring Data.

The third layer of the RESTful webapp onion is the business layer. This is the guts of the application – well-written persistence and webservice layers are constrained but anything goes in the business layer.

We’re only implementing CRUD methods at this point so these methods are straightforward.

Design Decisions

Spring Data – we will be using Spring Data for the persistence layer so we will want to specify the persistence layer interface with that in mind. As we’ll see in the next blog this greatly simplifies our life.

Limitations

DataAccessException – no attempt is made to throw different exceptions according to the type of DataAccessException we receive. This will be important later – we should treat a constraint violation differently than a lost database connection.

Service Interface

First a reminder of the service interface we identified in the last post.

public interface CourseService {
    List<Course> findAllCourses();

    Course findCourseById(Integer id);

    Course findCourseByUuid(String uuid);

    Course createCourse(String name);

    Course updateCourse(Course course, String name);

    void deleteCourse(String uuid);
}

Service Implementation

The service implementation goes quickly since it’s basic CRUD operations. Our only concerns are if there’s a problem with the database (DataAccessException in Spring) or if an expected value can’t be found. We need to add a new exception to our API for the former, already have an exception in the API for the latter.

public class CourseServiceImpl implements CourseService {
    private static final Logger log = LoggerFactory
            .getLogger(CourseServiceImpl.class);

    @Resource
    private CourseRepository courseRepository;

    /**
     * Default constructor
     */
    public CourseServiceImpl() {

    }

    /**
     * Constructor used in unit tests
     */
    CourseServiceImpl(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseService#
     *      findAllCourses()
     */
    @Transactional(readOnly = true)
    @Override
    public List<Course> findAllCourses() {
        List<Course> courses = null;

        try {
            courses = courseRepository.findAll();
        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("error loading list of courses: " + e.getMessage(), e);
            }
            throw new PersistenceException("unable to get list of courses.", e);
        }

        return courses;
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseService#
     *      findCourseById(java.lang.Integer)
     */
    @Transactional(readOnly = true)
    @Override
    public Course findCourseById(Integer id) {
        Course course = null;
        try {
            course = courseRepository.findOne(id);
        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("internal error retrieving course: " + id, e);
            }
            throw new PersistenceException("unable to find course by id", e, id);
        }

        if (course == null) {
            throw new ObjectNotFoundException(id);
        }

        return course;
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseService#
     *      findCourseByUuid(java.lang.String)
     */
    @Transactional(readOnly = true)
    @Override
    public Course findCourseByUuid(String uuid) {
        Course course = null;
        try {
            course = courseRepository.findCourseByUuid(uuid);
        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("internal error retrieving course: " + uuid, e);
            }
            throw new PersistenceException("unable to find course by uuid", e,
                    uuid);
        }

        if (course == null) {
            throw new ObjectNotFoundException(uuid);
        }

        return course;
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseService#
     *      createCourse(java.lang.String)
     */
    @Transactional
    @Override
    public Course createCourse(String name) {
        final Course course = new Course();
        course.setName(name);

        Course actual = null;
        try {
            actual = courseRepository.saveAndFlush(course);
        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("internal error retrieving course: " + name, e);
            }
            throw new PersistenceException("unable to create course", e);
        }

        return actual;
    }

    /**
     * @see com.invariantproperties.sandbox.course.persistence.CourseService#
     *      updateCourse(com.invariantproperties.sandbox.course.domain.Course,
     *      java.lang.String)
     */
    @Transactional
    @Override
    public Course updateCourse(Course course, String name) {
        Course updated = null;
        try {
            final Course actual = courseRepository.findCourseByUuid(course
                    .getUuid());

            if (actual == null) {
                log.debug("did not find course: " + course.getUuid());
                throw new ObjectNotFoundException(course.getUuid());
            }

            actual.setName(name);
            updated = courseRepository.saveAndFlush(actual);
            course.setName(name);

        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("internal error deleting course: " + course.getUuid(),
                        e);
            }
            throw new PersistenceException("unable to delete course", e,
                    course.getUuid());
        }

        return updated;
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseService#
     *      deleteCourse(java.lang.String)
     */
    @Transactional
    @Override
    public void deleteCourse(String uuid) {
        Course course = null;
        try {
            course = courseRepository.findCourseByUuid(uuid);

            if (course == null) {
                log.debug("did not find course: " + uuid);
                throw new ObjectNotFoundException(uuid);
            }
            courseRepository.delete(course);

        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("internal error deleting course: " + uuid, e);
            }
            throw new PersistenceException("unable to delete course", e, uuid);
        }
    }
}

This implementation tells us the required interface for the persistence layer.

Persistence Layer Interface

We will be using Spring Data for our persistence layer and our DAO interface is the same as a Spring Data repository. We only need one nonstandard method.

public class CourseServiceImplTest {

    @Test
    public void testFindAllCourses() {
        final List<Course> expected = Collections.emptyList();

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findAll()).thenReturn(expected);

        final CourseService service = new CourseServiceImpl(repository);
        final List<Course> actual = service.findAllCourses();

        assertEquals(expected, actual);
    }

    @Test(expected = PersistenceException.class)
    public void testFindAllCoursesError() {
        final List<Course> expected = Collections.emptyList();

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findAll()).thenThrow(new UnitTestException());

        final CourseService service = new CourseServiceImpl(repository);
        final List<Course> actual = service.findAllCourses();

        assertEquals(expected, actual);
    }

    @Test
    public void testFindCourseById() {
        final Course expected = new Course();
        expected.setId(1);

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findOne(any(Integer.class))).thenReturn(expected);

        final CourseService service = new CourseServiceImpl(repository);
        final Course actual = service.findCourseById(expected.getId());

        assertEquals(expected, actual);
    }

    @Test(expected = ObjectNotFoundException.class)
    public void testFindCourseByIdMissing() {
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findOne(any(Integer.class))).thenReturn(null);

        final CourseService service = new CourseServiceImpl(repository);
        service.findCourseById(1);
    }

    @Test(expected = PersistenceException.class)
    public void testFindCourseByIdError() {
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findOne(any(Integer.class))).thenThrow(
                new UnitTestException());

        final CourseService service = new CourseServiceImpl(repository);
        service.findCourseById(1);
    }

    @Test
    public void testFindCourseByUuid() {
        final Course expected = new Course();
        expected.setUuid("[uuid]");

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(
                expected);

        final CourseService service = new CourseServiceImpl(repository);
        final Course actual = service.findCourseByUuid(expected.getUuid());

        assertEquals(expected, actual);
    }

    @Test(expected = ObjectNotFoundException.class)
    public void testFindCourseByUuidMissing() {
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(null);

        final CourseService service = new CourseServiceImpl(repository);
        service.findCourseByUuid("[uuid]");
    }

    @Test(expected = PersistenceException.class)
    public void testFindCourseByUuidError() {
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenThrow(
                new UnitTestException());

        final CourseService service = new CourseServiceImpl(repository);
        service.findCourseByUuid("[uuid]");
    }

    @Test
    public void testCreateCourse() {
        final Course expected = new Course();
        expected.setName("name");
        expected.setUuid("[uuid]");

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.saveAndFlush(any(Course.class))).thenReturn(expected);

        final CourseService service = new CourseServiceImpl(repository);
        final Course actual = service.createCourse(expected.getName());

        assertEquals(expected, actual);
    }

    @Test(expected = PersistenceException.class)
    public void testCreateCourseError() {
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.saveAndFlush(any(Course.class))).thenThrow(
                new UnitTestException());

        final CourseService service = new CourseServiceImpl(repository);
        service.createCourse("name");
    }

    @Test
    public void testUpdateCourse() {
        final Course expected = new Course();
        expected.setName("Alice");
        expected.setUuid("[uuid]");

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(
                expected);
        when(repository.saveAndFlush(any(Course.class))).thenReturn(expected);

        final CourseService service = new CourseServiceImpl(repository);
        final Course actual = service.updateCourse(expected, "Bob");

        assertEquals("Bob", actual.getName());
    }

    @Test(expected = ObjectNotFoundException.class)
    public void testUpdateCourseMissing() {
        final Course expected = new Course();
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(null);

        final CourseService service = new CourseServiceImpl(repository);
        service.updateCourse(expected, "Bob");
    }

    @Test(expected = PersistenceException.class)
    public void testUpdateCourseError() {
        final Course expected = new Course();
        expected.setUuid("[uuid]");

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(
                expected);
        doThrow(new UnitTestException()).when(repository).saveAndFlush(
                any(Course.class));

        final CourseService service = new CourseServiceImpl(repository);
        service.updateCourse(expected, "Bob");
    }

    @Test
    public void testDeleteCourse() {
        final Course expected = new Course();
        expected.setUuid("[uuid]");

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(
                expected);
        doNothing().when(repository).delete(any(Course.class));

        final CourseService service = new CourseServiceImpl(repository);
        service.deleteCourse(expected.getUuid());
    }

    @Test(expected = ObjectNotFoundException.class)
    public void testDeleteCourseMissing() {
        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(null);

        final CourseService service = new CourseServiceImpl(repository);
        service.deleteCourse("[uuid]");
    }

    @Test(expected = PersistenceException.class)
    public void testDeleteCourseError() {
        final Course expected = new Course();
        expected.setUuid("[uuid]");

        final CourseRepository repository = Mockito
                .mock(CourseRepository.class);
        when(repository.findCourseByUuid(any(String.class))).thenReturn(
                expected);
        doThrow(new UnitTestException()).when(repository).delete(
                any(Course.class));

        final CourseService service = new CourseServiceImpl(repository);
        service.deleteCourse(expected.getUuid());
    }
}

Integration Testing

Integration testing has been deferred until the persistence layer is implemented.

Source Code

 

Reference: Project Student: Business Layer from our JCG partner Bear Giles at the Invariant Properties blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


1 × four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books