com.github.jens_meiss.blog.server.service.impl.BlogServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.github.jens_meiss.blog.server.service.impl.BlogServiceImpl.java

Source

/*
 * This file is part of blog (https://github.com/jens-meiss/blog).
 *
 *  blog is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  blog is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with blog. If not, see <http://www.gnu.org/licenses/>.
 */
package com.github.jens_meiss.blog.server.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.jens_meiss.blog.server.persistence.entity.BlogEntity;
import com.github.jens_meiss.blog.server.persistence.entity.BlogEntryEntity;
import com.github.jens_meiss.blog.server.persistence.entity.UserEntity;
import com.github.jens_meiss.blog.server.persistence.repository.repositories.BlogEntryRepository;
import com.github.jens_meiss.blog.server.persistence.repository.repositories.BlogRepository;
import com.github.jens_meiss.blog.server.persistence.repository.repositories.UserRepository;
import com.github.jens_meiss.blog.service.BlogService;
import com.github.jens_meiss.blog.service.TimeService;
import com.github.jens_meiss.blog.service.UserService;
import com.github.jens_meiss.blog.service.dto.blog.BlogAddDTO;
import com.github.jens_meiss.blog.service.dto.blog.BlogDTO;
import com.github.jens_meiss.blog.service.dto.blog.BlogRemoveDTO;
import com.github.jens_meiss.blog.service.dto.blog.BlogUpdateDTO;
import com.github.jens_meiss.blog.service.dto.blog.entry.BlogEntryDTO;
import com.github.jens_meiss.blog.service.dto.home.PopularBlogDTO;
import com.github.jens_meiss.blog.service.dto.impl.blog.BlogDTOImpl;
import com.github.jens_meiss.blog.service.dto.impl.blog.entry.BlogEntryDTOImpl;
import com.github.jens_meiss.blog.service.dto.impl.home.PopulardBlogDTOImpl;
import com.github.jens_meiss.blog.service.dto.user.UserRemoveDTO;

/**
 * BlogServiceImpl.
 */
@Service
@Transactional(readOnly = true)
public class BlogServiceImpl implements BlogService {

    /** The Constant logger. */
    private static final Logger logger = LoggerFactory.getLogger(BlogServiceImpl.class);

    /**
     * Blog entities to blog dt os.
     *
     * @param blogEntities the blog entities
     * @return the list
     */
    private static final List<BlogDTO> blogEntitiesToBlogDTOs(final List<BlogEntity> blogEntities) {

        logger.debug("blogEntitiesToBlogDTOs");

        if ((blogEntities == null) || (blogEntities.size() == 0))
            return Collections.emptyList();

        final List<BlogDTO> blogDTOs = new LinkedList<BlogDTO>();
        for (final BlogEntity blogEntity : blogEntities) {

            final BlogDTO blogDTO = blogEntityToBlogDTO(blogEntity);

            blogDTOs.add(blogDTO);
        }

        return blogDTOs;

    }

    /**
     * Blog entity to blog dto.
     *
     * @param blogEntity the blog entity
     * @return the blog dto impl
     */
    public static BlogDTOImpl blogEntityToBlogDTO(final BlogEntity blogEntity) {

        logger.debug("blogEntityToBlogDTO");

        if (blogEntity == null)
            return null;

        return fillBlogDetails(blogEntity);

    }

    /**
     * Blog entry to popular blog dto.
     *
     * @param entities the entities
     * @return the list
     */
    public static List<PopularBlogDTO> blogEntryToPopularBlogDTO(final List<BlogEntity> entities) {

        final List<PopularBlogDTO> popularBlogs = new LinkedList<PopularBlogDTO>();
        for (final BlogEntity blogEntity : entities) {

            final PopulardBlogDTOImpl popularBlog = new PopulardBlogDTOImpl();
            popularBlog.setAuthor("Author of Blog " + blogEntity.getPath());
            popularBlog.setDateLastUpdate(blogEntity.getDateLastUpdated());
            popularBlog.setPath(blogEntity.getPath());
            popularBlog.setPreview("preview");
            popularBlog.setTitle(blogEntity.getTitle());
            popularBlog.setVisitsPerDay(blogEntity.getVisitsPerDay());

            popularBlogs.add(popularBlog);
        }

        return popularBlogs;
    }

    /**
     * Fill blog details.
     *
     * @param blogEntity the blog entity
     * @return the blog dto impl
     */
    private static BlogDTOImpl fillBlogDetails(final BlogEntity blogEntity) {

        final BlogDTOImpl blogDTO = new BlogDTOImpl();

        if (blogEntity == null) {
            logger.error("blogEntry is empty");

            blogDTO.setDateLastUpdated(new Date());
            blogDTO.setDescription("Blog Description");
            blogDTO.setTitle("Blog Title");
            blogDTO.setAuthor("Author of Blog");

        } else {
            blogDTO.setDateLastUpdated(blogEntity.getDateLastUpdated());
            blogDTO.setDescription(blogEntity.getDescription());
            blogDTO.setTitle(blogEntity.getTitle());
            blogDTO.setAuthor("Author of Blog " + blogEntity.getPath());
            blogDTO.setPath(blogEntity.getPath());
        }

        return blogDTO;

    }

    /**
     * Fill blog entries.
     *
     * @param entries the entries
     * @param blogDTO the blog dto
     */
    private static void fillBlogEntries(final List<BlogEntryEntity> entries, final BlogDTOImpl blogDTO) {

        final List<BlogEntryDTO> blogEntries = new LinkedList<BlogEntryDTO>();

        if ((entries != null) && (entries.size() > 0)) {

            BlogEntryDTOImpl blogEntryDTO;
            for (final BlogEntryEntity blogEntryEntity : entries) {

                blogEntryDTO = new BlogEntryDTOImpl();
                blogEntryDTO.setId(blogEntryEntity.getId());
                blogEntryDTO.setDate(blogEntryEntity.getDate());
                blogEntryDTO.setText(blogEntryEntity.getText());
                blogEntryDTO.setBlogPath(blogDTO.getPath());

                blogEntries.add(blogEntryDTO);
            }
        }

        blogDTO.setEntries(blogEntries);
    }

    /** The blog entry repository. */
    @Autowired
    private BlogEntryRepository blogEntryRepository;

    /** The blog repository. */
    @Autowired
    private BlogRepository blogRepository;

    /** The time service. */
    @Autowired
    private TimeService timeService;

    /** The user repository. */
    @Autowired
    private UserRepository userRepository;

    /** The user service. */
    @Autowired
    private UserService userService;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Secured("ROLE_USER")
    @Override
    public boolean add(final BlogAddDTO blogAddDTO) {

        logger.debug("add");

        final String blogPath = blogAddDTO.getPath();

        final BlogEntity blogEntity = blogRepository.findByPath(blogPath);
        if (blogEntity != null)
            return false;

        BlogEntity entity = new BlogEntity();
        entity.setDateLastUpdated(timeService.getCurrentDate());
        entity.setDescription(blogAddDTO.getDescription());
        entity.setPath(blogAddDTO.getPath());
        entity.setTitle(blogAddDTO.getTitle());
        entity.setUser(userRepository.findByUserName(userService.getCurrentUser().getName()));
        entity.setVisitsPerDay(0);

        entity = blogRepository.save(entity);

        return true;

    }

    /**
     * Find blog.
     *
     * @param path the path
     * @return the blog entity
     */
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    private BlogEntity findBlog(final String path) {

        logger.debug("findBlog");

        final BlogEntity blog = blogRepository.findByPath(path);
        if (blog == null) {
            logger.warn("blog with id '" + path + "' does not exist");
            return null;
        }

        return blog;
    }

    @Secured("ROLE_USER")
    @Override
    public int findBlogsByUserId(final long userId) {

        logger.debug("finBlogsByUserId");

        // final UserUpdateDTO userUpdateDTO = userService.getCurrentUser();

        final List<BlogEntity> entities = blogRepository.findAllByUserId(userId);

        return entities.size();
    }

    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    @Override
    public BlogDTO getBlog(final String blogPath) {

        logger.debug("getBlog");

        final BlogEntity blogEntity = blogRepository.findByPath(blogPath);
        final BlogDTOImpl blogDTO = blogEntityToBlogDTO(blogEntity);

        final Page<BlogEntryEntity> page = blogEntryRepository.findByBlog(blogEntity,
                new PageRequest(0, 10, new Sort(new Sort.Order(Direction.DESC, "date"))));
        fillBlogEntries(page.getContent(), blogDTO);

        return blogDTO;
    }

    @Secured("ROLE_USER")
    @Override
    public List<BlogDTO> getBlogsByUserID(final long userId, final int startIndex, final int length) {

        logger.debug("getBlogsByUserID");

        final List<BlogEntity> blogEntities = blogRepository.findAllByUserId(userId,
                new PageRequest(startIndex, length));

        return blogEntitiesToBlogDTOs(blogEntities);
    }

    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    @Override
    public List<PopularBlogDTO> getPopularBlogs(final int startIndex, final int length) {

        logger.debug("getPopularBlogs");

        final Page<BlogEntity> page = blogRepository.findAll(
                new PageRequest(startIndex, length, new Sort(new Sort.Order(Direction.DESC, "visitsPerDay"),
                        new Sort.Order(Direction.DESC, "dateLastUpdated"))));

        final List<PopularBlogDTO> popularBlogs = blogEntryToPopularBlogDTO(page.getContent());

        final PopulardBlogDTOImpl popularBlogDTO = new PopulardBlogDTOImpl();
        popularBlogDTO.setAuthor("author");
        popularBlogDTO.setDateLastUpdate(new Date(System.currentTimeMillis() + 1000));
        popularBlogDTO.setPath("path");
        popularBlogDTO.setPreview("preview");
        popularBlogDTO.setTitle("title");
        popularBlogDTO.setVisitsPerDay(12345);

        popularBlogs.add(popularBlogDTO);

        return popularBlogs;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    @Override
    public void increaseVisitsPerDay(final BlogDTO blogDTO) {

        logger.debug("increaseVisitsPerDay");

        final BlogEntity entity = blogRepository.findByPath(blogDTO.getPath());
        if (entity == null)
            return;

        final long visitsPerDay = entity.getVisitsPerDay();
        entity.setVisitsPerDay(visitsPerDay + 1);

        blogRepository.save(entity);

    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Secured("ROLE_USER")
    @Override
    public boolean remove(final BlogRemoveDTO blogRemoveDTO) {

        logger.debug("remove");

        final String path = blogRemoveDTO.getPath();

        final BlogEntity blog = findBlog(path);
        if (blog == null)
            return false;

        blogRepository.delete(blog);

        return true;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Secured("ROLE_USER")
    @Override
    public void removeAll(final long userId) {

        logger.debug("removeAll");

    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Secured("ROLE_USER")
    @Override
    public void removeAllByUser(final UserRemoveDTO userRemoveDTO) {

        logger.debug("removeAllByUser");

        final UserEntity userEntity = userRepository.findOne(userRemoveDTO.getUserId());
        final List<BlogEntity> entities = blogRepository.findAllByUser(userEntity);

        blogRepository.deleteInBatch(entities);

    }

    /**
     * Sets the blog entry repository.
     *
     * @param blogEntryRepository the new blog entry repository
     */
    public void setBlogEntryRepository(final BlogEntryRepository blogEntryRepository) {
        this.blogEntryRepository = blogEntryRepository;
    }

    /**
     * Sets the blog repository.
     *
     * @param blogRepository the new blog repository
     */
    public void setBlogRepository(final BlogRepository blogRepository) {
        this.blogRepository = blogRepository;
    }

    /**
     * Sets the time service.
     *
     * @param timeService the new time service
     */
    public void setTimeService(final TimeService timeService) {
        this.timeService = timeService;
    }

    /**
     * Sets the user repository.
     *
     * @param userRepository the new user repository
     */
    public void setUserRepository(final UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * Sets the user service.
     *
     * @param userService the new user service
     */
    public void setUserService(final UserService userService) {
        this.userService = userService;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Secured("ROLE_USER")
    @Override
    public boolean update(final BlogUpdateDTO blogUpdateDTO) {

        logger.debug("update");

        final String path = blogUpdateDTO.getPath();

        final BlogEntity blog = findBlog(path);
        if (blog == null)
            return false;

        blog.setDateLastUpdated(blogUpdateDTO.getDateLastUpdate());
        blog.setTitle(blogUpdateDTO.getTitle());
        blog.setDescription(blogUpdateDTO.getDescription());

        blogRepository.save(blog);

        return true;
    }
}