com.aripd.clms.service.ContractServiceBean.java Source code

Java tutorial

Introduction

Here is the source code for com.aripd.clms.service.ContractServiceBean.java

Source

package com.aripd.clms.service;

import com.aripd.clms.entity.ContractEntity;
import com.aripd.clms.entity.ContractEntity_;
import com.aripd.clms.entity.CollaboratorEntity;
import com.aripd.clms.entity.CollaboratorEntity_;
import com.aripd.clms.entity.HistoryContractEntity;
import com.aripd.clms.entity.UserEntity;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.BadPdfFormatException;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfImage;
import com.lowagie.text.pdf.PdfIndirectObject;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.model.SortMeta;
import org.primefaces.model.SortOrder;

@Stateless
public class ContractServiceBean extends CrudServiceBean<ContractEntity, Long> implements ContractService {

    @Inject
    private HistoryContractService historyContractService;

    @PersistenceContext
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ContractServiceBean() {
        super(ContractEntity.class);
    }

    @Override
    public List<ContractEntity> getResultListByUser(UserEntity user, int first, int pageSize, String sortField,
            SortOrder sortOrder, Map<String, Object> filters) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        Root<ContractEntity> root = cq.from(ContractEntity.class);
        Join<ContractEntity, CollaboratorEntity> collaborators = root.join(ContractEntity_.collaborators);

        Predicate predicate1 = cb.equal(collaborators.get(CollaboratorEntity_.user), user);
        Predicate predicate2 = this.getFilterCondition(cb, root, filters);

        Predicate predicate = cb.and(predicate1, predicate2);
        cq.where(predicate);

        if (sortField != null) {
            if (sortOrder == SortOrder.ASCENDING) {
                cq.orderBy(cb.asc(root.get(sortField)));
            } else if (sortOrder == SortOrder.DESCENDING) {
                cq.orderBy(cb.desc(root.get(sortField)));
            }
        } else {
            cq.orderBy(cb.desc(root.get(ContractEntity_.id)));
        }
        Query q = getEntityManager().createQuery(cq);
        return q.setFirstResult(first).setMaxResults(pageSize).getResultList();
    }

    @Override
    public List<ContractEntity> getResultListByUser(UserEntity user, int first, int pageSize,
            List<SortMeta> multiSortMeta, Map<String, Object> filters) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        Root<ContractEntity> root = cq.from(ContractEntity.class);
        Join<ContractEntity, CollaboratorEntity> collaborators = root.join(ContractEntity_.collaborators);

        Predicate predicate1 = cb.equal(collaborators.get(CollaboratorEntity_.user), user);
        Predicate predicate2 = this.getFilterCondition(cb, root, filters);

        Predicate predicate = cb.and(predicate1, predicate2);
        cq.where(predicate);

        if (multiSortMeta != null) {
            List<Order> orders = new ArrayList<>();
            for (SortMeta sortMeta : multiSortMeta) {
                String sortField = sortMeta.getSortField();
                SortOrder sortOrder = sortMeta.getSortOrder();
                if (sortField != null) {
                    Order order = null;
                    if (sortOrder == SortOrder.ASCENDING) {
                        order = cb.asc(root.get(sortField));
                    } else if (sortOrder == SortOrder.DESCENDING) {
                        order = cb.desc(root.get(sortField));
                    }
                    orders.add(order);
                }
            }
            cq.orderBy(orders);
        } else {
            cq.orderBy(cb.desc(root.get(ContractEntity_.id)));
        }

        Query q = getEntityManager().createQuery(cq);
        return q.setFirstResult(first).setMaxResults(pageSize).getResultList();
    }

    @Override
    public int countByUser(UserEntity user, Map<String, Object> filters) {
        try {
            CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
            CriteriaQuery<Long> cq = cb.createQuery(Long.class);
            Root<ContractEntity> root = cq.from(ContractEntity.class);
            Join<ContractEntity, CollaboratorEntity> collaborators = root.join(ContractEntity_.collaborators);

            Predicate predicate1 = cb.equal(collaborators.get(CollaboratorEntity_.user), user);
            Predicate predicate2 = this.getFilterCondition(cb, root, filters);

            Predicate predicate = cb.and(predicate1, predicate2);
            cq.where(predicate);

            cq.select(cb.count(root));

            return getEntityManager().createQuery(cq).getSingleResult().intValue();
        } catch (NoResultException ex) {
            return 0;
        }
    }

    @Override
    public List<ContractEntity> getResultList(String searchTerms, int first, int pageSize, String sortField,
            SortOrder sortOrder, Map<String, Object> filters) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        Root<ContractEntity> root = cq.from(ContractEntity.class);

        List<Predicate> andPredicates2 = new ArrayList<>();
        List<Predicate> andPredicates3 = new ArrayList<>();

        if (searchTerms != null) {
            String[] searchTerm = searchTerms.split("\\s+");
            for (int i = 0; i < searchTerm.length; i++) {
                andPredicates2.add(cb.like(root.get(ContractEntity_.name), "%" + searchTerm[i] + "%"));
                andPredicates3.add(cb.like(root.get(ContractEntity_.remark), "%" + searchTerm[i] + "%"));
            }
        }

        Predicate predicates2 = cb.and(andPredicates2.toArray(new Predicate[andPredicates2.size()]));
        Predicate predicates3 = cb.and(andPredicates3.toArray(new Predicate[andPredicates3.size()]));

        Predicate predicate1 = this.getFilterCondition(cb, root, filters);
        Predicate predicate5 = cb.or(predicates2, predicates3);

        Predicate predicate = cb.and(predicate1, predicate5);
        cq.where(predicate);

        if (sortField != null) {
            if (sortOrder == SortOrder.ASCENDING) {
                cq.orderBy(cb.asc(root.get(sortField)));
            } else if (sortOrder == SortOrder.DESCENDING) {
                cq.orderBy(cb.desc(root.get(sortField)));
            }
        }

        cq.orderBy(cb.desc(root.get(ContractEntity_.id)));

        Query q = getEntityManager().createQuery(cq);
        return q.setFirstResult(first).setMaxResults(pageSize).getResultList();
    }

    @Override
    public List<ContractEntity> getResultList(String searchTerms, int first, int pageSize,
            List<SortMeta> multiSortMeta, Map<String, Object> filters) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        Root<ContractEntity> root = cq.from(ContractEntity.class);

        List<Predicate> andPredicates2 = new ArrayList<>();
        List<Predicate> andPredicates3 = new ArrayList<>();

        if (searchTerms != null) {
            String[] searchTerm = searchTerms.split("\\s+");
            for (int i = 0; i < searchTerm.length; i++) {
                andPredicates2.add(cb.like(root.get(ContractEntity_.name), "%" + searchTerm[i] + "%"));
                andPredicates3.add(cb.like(root.get(ContractEntity_.remark), "%" + searchTerm[i] + "%"));
            }
        }

        Predicate predicates2 = cb.and(andPredicates2.toArray(new Predicate[andPredicates2.size()]));
        Predicate predicates3 = cb.and(andPredicates3.toArray(new Predicate[andPredicates3.size()]));

        Predicate predicate1 = this.getFilterCondition(cb, root, filters);
        Predicate predicate5 = cb.or(predicates2, predicates3);

        Predicate predicate = cb.and(predicate1, predicate5);
        cq.where(predicate);

        if (multiSortMeta != null) {
            List<Order> orders = new ArrayList<>();
            for (SortMeta sortMeta : multiSortMeta) {
                String sortField = sortMeta.getSortField();
                SortOrder sortOrder = sortMeta.getSortOrder();
                if (sortField != null) {
                    Order order = null;
                    if (sortOrder == SortOrder.ASCENDING) {
                        order = cb.asc(root.get(sortField));
                    } else if (sortOrder == SortOrder.DESCENDING) {
                        order = cb.desc(root.get(sortField));
                    }
                    orders.add(order);
                }
            }
            cq.orderBy(orders);
        } else {
            cq.orderBy(cb.desc(root.get(ContractEntity_.id)));
        }

        Query q = getEntityManager().createQuery(cq);
        return q.setFirstResult(first).setMaxResults(pageSize).getResultList();
    }

    @Override
    public int count(String searchTerms, Map<String, Object> filters) {
        try {
            CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
            CriteriaQuery<Long> cq = cb.createQuery(Long.class);
            Root<ContractEntity> root = cq.from(ContractEntity.class);

            List<Predicate> andPredicates2 = new ArrayList<>();
            List<Predicate> andPredicates3 = new ArrayList<>();

            if (searchTerms != null) {
                String[] searchTerm = searchTerms.split("\\s+");
                for (int i = 0; i < searchTerm.length; i++) {
                    andPredicates2.add(cb.like(root.get(ContractEntity_.name), "%" + searchTerm[i] + "%"));
                    andPredicates3.add(cb.like(root.get(ContractEntity_.remark), "%" + searchTerm[i] + "%"));
                }
            }

            Predicate predicates2 = cb.and(andPredicates2.toArray(new Predicate[andPredicates2.size()]));
            Predicate predicates3 = cb.and(andPredicates3.toArray(new Predicate[andPredicates3.size()]));

            Predicate predicate1 = this.getFilterCondition(cb, root, filters);
            Predicate predicate5 = cb.or(predicates2, predicates3);

            Predicate predicate = cb.and(predicate1, predicate5);
            cq.where(predicate);

            cq.select(cb.count(root));

            return getEntityManager().createQuery(cq).getSingleResult().intValue();
        } catch (NoResultException ex) {
            return 0;
        }
    }

    @Override
    public void generatePdf(ContractEntity contract) {
        String baseFontUrl = "/fonts/Quivira.otf";
        FontFactory.register(baseFontUrl);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            BaseFont bf = BaseFont.createFont(baseFontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font font18n = new Font(bf, 18, Font.NORMAL);
            Font font12n = new Font(bf, 12, Font.NORMAL);
            Font font8n = new Font(bf, 8, Font.NORMAL);
            Font font8nbu = new Font(bf, 8, Font.BOLD | Font.UNDERLINE);
            Font font8ng = new Font(bf, 8, Font.NORMAL, Color.DARK_GRAY);
            Font font6n = new Font(bf, 6, Font.NORMAL);

            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document, output);
            document.open();
            addMetaData(document);
            addTitlePage(document, contract);
            Image imgBlue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte) 0, (byte) 0, (byte) 255, });
            imgBlue.scaleAbsolute(document.getPageSize().getWidth(), 10);
            imgBlue.setAbsolutePosition(0, document.getPageSize().getHeight() - imgBlue.getScaledHeight());
            PdfImage stream = new PdfImage(imgBlue, "", null);
            stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
            PdfIndirectObject ref = writer.addToBody(stream);
            imgBlue.setDirectReference(ref.getIndirectReference());
            document.add(imgBlue);

            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(100);

            PdfPCell cell = new PdfPCell(new Paragraph(contract.getName(), font18n));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setColspan(2);
            cell.setPadding(5);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Version: " + contract.getVersion(), font8n));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setColspan(2);
            cell.setPadding(5);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Review: " + contract.getReview(), font8n));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setColspan(2);
            cell.setPadding(5);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(contract.getRemark(), font12n));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setColspan(2);
            cell.setPadding(5);
            table.addCell(cell);
            document.add(table);
            // Start a new page
            document.newPage();

            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.parse(new StringReader(contract.getRemark()));
            // Start a new page
            document.newPage();

            document.add(new Paragraph("Review Board", font18n));
            document.add(new LineSeparator(0.5f, 100, null, 0, -5));

            table = new PdfPTable(3);
            table.setWidthPercentage(100);

            cell = new PdfPCell(new Paragraph("Review Board", font18n));
            cell.setColspan(3);
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Version", font12n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Date", font12n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph("Review", font12n));
            table.addCell(cell);
            for (HistoryContractEntity history : historyContractService.listing(contract)) {
                cell = new PdfPCell(new Paragraph(history.getVersion().toString(), font8n));
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(history.getStartdate().toString(), font8n));
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(history.getReview(), font8n));
                table.addCell(cell);
            }
            document.add(table);

            document.close();

            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
            response.reset();
            response.addHeader("Content-Type", "application/force-download");
            String filename = URLEncoder.encode(contract.getName() + ".pdf", "UTF-8");
            //            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
            response.getOutputStream().write(output.toByteArray());
            response.getOutputStream().flush();
            context.responseComplete();
            context.renderResponse();

        } catch (BadPdfFormatException | IOException ex) {
            Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private static void addMetaData(Document document) {
        document.addTitle("Generated PDF for CLMS");
        document.addSubject("Using iText");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("dev@aripd.com");
        document.addCreator("dev@aripd.com");
    }

    private static void addTitlePage(Document document, ContractEntity contract) throws DocumentException {
        Paragraph preface = new Paragraph();
        // We add one empty line
        addEmptyLine(preface, 1);
        // Lets write a big header
        preface.add(new Paragraph(contract.getName()));

        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date()));
        addEmptyLine(preface, 3);
        preface.add(new Paragraph("This document describes something which is very important "));

        addEmptyLine(preface, 8);

        preface.add(
                new Paragraph("This document is a preliminary version and not subject to your license agreement."));

        document.add(preface);
        // Start a new page
        document.newPage();
    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }

}