no.dusken.barweb.view.InvoiceView.java Source code

Java tutorial

Introduction

Here is the source code for no.dusken.barweb.view.InvoiceView.java

Source

/*
 Copyright 2009 - 2010 Under Dusken
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package no.dusken.barweb.view;

import no.dusken.barweb.model.BarPerson;
import no.dusken.barweb.model.Gjeng;
import no.dusken.barweb.model.Invoice;
import no.dusken.barweb.util.InvoiceUtils;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.AbstractView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Marvin B. Lillehaug <lillehau@underdusken.no>
 */
public class InvoiceView extends AbstractView {
    private Logger log = LoggerFactory.getLogger(getClass());
    private String styleSheet = "invoice-fo.xsl";
    private FopFactory fopFactory = FopFactory.newInstance();
    private TransformerFactory tFactory = TransformerFactory.newInstance();

    protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=faktura.pdf");

        Map<BarPerson, Integer> persons = (Map<BarPerson, Integer>) model.get("persons");
        Gjeng g = (Gjeng) model.get("gjeng");
        Invoice invoice = (Invoice) model.get("invoice");
        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, response.getOutputStream());

        //Setup Transformer
        Source xsltSrc = new StreamSource(
                this.getClass().getResourceAsStream("/no/dusken/barweb/stylesheets/" + styleSheet));
        Transformer transformer = tFactory.newTransformer(xsltSrc);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Setup input
        DOMSource src = new DOMSource(generateXml(persons, g, invoice));

        //Start the transformation and rendering process
        transformer.transform(src, res);
        response.getOutputStream().flush();

    }

    private Document generateXml(Map<BarPerson, Integer> persons, Gjeng gjeng, Invoice invoice) {
        Document dom = null;
        //get an instance of factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            //get an instance of builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //create an instance of DOM
            dom = db.newDocument();

        } catch (ParserConfigurationException pce) {
            log.error("Error when generating invoice");
        }
        Element root = createInvoiceElement(invoice, gjeng, dom);
        SimpleDateFormat dateformat = new SimpleDateFormat("dd. MMMMMMMMM yyyy - HH:mm", new Locale("no"));
        root.setAttribute("generated", dateformat.format((new GregorianCalendar()).getTime()));
        root.setAttribute("magicNumber", String.valueOf(((new Random()).nextDouble() * 1000)));
        dom.appendChild(root);
        Element personsEle = dom.createElement("persons");

        for (Map.Entry<BarPerson, Integer> p : persons.entrySet()) {
            Element personEle = createPersonElement(p.getKey(), p.getValue(), dom);
            personsEle.appendChild(personEle);
        }

        root.appendChild(personsEle);

        return dom;
    }

    private Element createInvoiceElement(Invoice invoice, Gjeng gjeng, Document dom) {
        Element root = dom.createElement("invoice");
        root.setAttribute("gjeng", gjeng.getName());
        root.setAttribute("invoiceID", invoice.getId().toString());
        root.setAttribute("invoiceSum", String.valueOf(invoice.getSum()));
        root.setAttribute("comment", invoice.getComment());
        SimpleDateFormat dateformat = new SimpleDateFormat("dd. MMMMMMMMM yyyy", new Locale("no"));
        Calendar earliest = InvoiceUtils.getEarliestTransaksjonCalendar(invoice);
        Calendar latest = InvoiceUtils.getLatestTransaksjonCalendar(invoice);
        String timespan = null;
        if (earliest != null && latest != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(dateformat.format(earliest.getTime()));
            sb.append(" - ");
            sb.append(dateformat.format(latest.getTime()));
            timespan = sb.toString();
        }
        root.setAttribute("timespan", timespan);
        return root;
    }

    private Element createPersonElement(BarPerson p, Integer owes, Document dom) {
        Element personEle = dom.createElement("person");
        personEle.setTextContent(p.getName());
        personEle.setAttribute("owes", owes.toString());
        return personEle;
    }
}