com.prime.location.billing.InvoicedBillingManager.java Source code

Java tutorial

Introduction

Here is the source code for com.prime.location.billing.InvoicedBillingManager.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.prime.location.billing;

import com.kahlon.guard.controller.AbstractPerson;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.prime.app.location.Location;
import com.prime.app.util.DateUtility;
import com.prime.report.template.TableHeader;
import java.awt.Color;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.io.output.ByteArrayOutputStream;

/**
 * Agency Invoiced Billing Manager
 *
 * @author prime
 */
@Named("invoicedBilling")
@ViewScoped
public class InvoicedBillingManager extends AbstractPerson implements Serializable {

    private static final long serialVersionUID = 9196263323752494128L;

    @Inject
    AgencyBillingService service;

    @Inject
    Logger logger;

    @Inject
    FacesContext facesContext;

    private Location selectedAgency;
    private AgencyInvoice selectedInvoice;

    private List<AgencyInvoice> invoices = new ArrayList<>();

    @PostConstruct
    public void init() {
        logger.log(Level.INFO, "Initialize Agency Invoiced Billing Manager");
    }

    /**
     * Total Pending Billing
     *
     * @return
     */
    public String getTotalPending() {
        int total = 0;
        List<AgencyBilling> billings = service.findWithNamedQuery(AgencyBilling.TOTAL_PENDING_INVOICE);
        for (AgencyBilling billing : billings) {
            total += billing.getRate().intValue();
        }

        return new DecimalFormat("US$ ###,###.###").format(total);

    }

    /**
     * Print invoice
     */
    public void printInvoice() {
        try { //catch better your exceptions, this is just an example
            FacesContext context = FacesContext.getCurrentInstance();

            Document pdf = new Document(PageSize.A4, 5f, 5f, 75f, 45f);

            String fileName = "PDFFile";

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(pdf, baos);
            TableHeader event = new TableHeader();
            event.setHeader("Header Here");
            writer.setPageEvent(event);

            if (!pdf.isOpen()) {
                pdf.open();
            }

            PdfPCell cell;

            PdfPTable header = new PdfPTable(new float[] { 1, 2, 1 });
            cell = new PdfPCell(new Paragraph("INVOICE",
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC, Color.BLACK)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(3);
            cell.setBorder(Rectangle.NO_BORDER);
            header.addCell(cell);
            header.setTotalWidth(527);
            header.setLockedWidth(true);

            cell = new PdfPCell(new Phrase("Agency: " + selectedAgency.getDescription()));
            cell.setColspan(2);
            cell.setBorder(Rectangle.NO_BORDER);
            header.addCell(cell);

            cell = new PdfPCell(new Phrase("Invoice#: " + selectedInvoice.getId()));
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            header.addCell(cell);

            cell = new PdfPCell(
                    new Phrase("Date: " + DateUtility.dateTimeFormat(selectedInvoice.getInvoiceDate())));
            cell.setColspan(3);
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            header.addCell(cell);

            pdf.add(header);

            PdfPTable table = new PdfPTable(new float[] { 1, 3, 2, 1 });
            table.setSpacingBefore(15f);

            table.setTotalWidth(527);
            table.setLockedWidth(true);
            //table.setWidths(new int[]{3, 1, 1});

            table.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);

            table.addCell("Date");
            table.addCell("Name");
            table.addCell("Service");
            table.addCell("Rate");

            table.getDefaultCell().setBackgroundColor(null);

            cell = new PdfPCell(new Phrase("Total(US$): "));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setColspan(3);
            cell.setBackgroundColor(Color.LIGHT_GRAY);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(selectedInvoice.getAmount())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setBackgroundColor(Color.LIGHT_GRAY);
            table.addCell(cell);

            // There are three special rows
            table.setHeaderRows(2);
            // One of them is a footer
            table.setFooterRows(1);
            Font f = FontFactory.getFont(FontFactory.HELVETICA, 10);
            //add remaining
            for (AgencyBilling billing : selectedInvoice.getBillings()) {
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.getDefaultCell().setIndent(2);
                table.getDefaultCell().setFixedHeight(20);

                table.addCell(new Phrase(DateUtility.dateFormat(billing.getBillingDate()), f));
                table.addCell(new Phrase(billing.getPerson().getName(), f));
                table.addCell(new Phrase(billing.getTariff().getTariffType().getDescription(), f));
                cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(billing.getRate()), f));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

                table.addCell(cell);

            }

            pdf.add(table);

            writer.getAcroForm().setNeedAppearances(true);

            //document.add(new Phrase(TEXT));
            //Keep modifying your pdf file (add pages and more)
            pdf.close();

            writePDFToResponse(context.getExternalContext(), baos, fileName);

            context.responseComplete();

        } catch (Exception e) {
            //e.printStackTrace();          
        }
    }

    private void writePDFToResponse(ExternalContext externalContext, ByteArrayOutputStream baos, String fileName) {
        try {
            externalContext.responseReset();
            externalContext.setResponseContentType("application/pdf");
            externalContext.setResponseHeader("Expires", "0");
            externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            externalContext.setResponseHeader("Pragma", "public");
            //externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
            externalContext.setResponseHeader("Content-disposition", "inline;filename=" + fileName + ".pdf");
            externalContext.setResponseContentLength(baos.size());
            OutputStream out = externalContext.getResponseOutputStream();
            baos.writeTo(out);
            externalContext.responseFlushBuffer();
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    //getter and setter
    public Location getSelectedAgency() {
        return selectedAgency;
    }

    public void setSelectedAgency(Location selectedAgency) {
        this.selectedAgency = selectedAgency;
        invoices = service.findWithParentId(AgencyInvoice.ALL, selectedAgency.getId());

    }

    public AgencyInvoice getSelectedInvoice() {
        return selectedInvoice;
    }

    public void setSelectedInvoice(AgencyInvoice selectedInvoice) {
        this.selectedInvoice = selectedInvoice;
        printInvoice();
    }

    public List<AgencyInvoice> getInvoices() {
        return invoices;
    }

    public void setInvoices(List<AgencyInvoice> invoices) {
        this.invoices = invoices;
    }

}