Java tutorial
/* * Copyright 2007-2009 Alexander Fabisch * * 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 com.ev.export; import com.ev.datamodel.*; import com.ev.gui.MainFrame; import com.ev.logic.*; import com.lowagie.text.*; import com.lowagie.text.pdf.PdfWriter; import java.awt.Color; import java.io.*; import java.text.DecimalFormat; import javax.swing.JFileChooser; import org.apache.log4j.Logger; import org.jfree.chart.*; import org.jfree.chart.plot.PlotOrientation; import static com.ev.global.GlobalConfiguration.*; import static com.ev.global.Constants.*; /** * Exports the data of a year and the chart into a PDF destination. * * @author <a href="mailto:afabisch@tzi.de">Alexander Fabisch</a> * @since 0.8.2 */ public final class AnnualPDFExporter extends ExporterTemplate { private static final Logger LOGGER = Logger.getLogger(AnnualPDFExporter.class); private static final Font TABLE_HEAD_FONT = new Font(Font.HELVETICA, 16, Font.BOLD, Color.GRAY); /** The maximum expected export time is used to find out if a destination has to be deleted if the export * failes. */ private static final long EXPECTED_MAX_EXPORT_TIME = 2000L; private final int year; private CounterOfAYear counter; private JFreeChart chart; private AnnualConsumption consumption; private Document document; private Table table; /** * Creates a PDFExporter Object. * @param year The year to export. */ public AnnualPDFExporter(int year) { this.year = year; counter = CounterOfAYearFactory.getCounterOfAYear(year); consumption = new AnnualConsumption(counter); document = new Document(); } @Override public String chooseFile() throws IOException { JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jfc.showSaveDialog(MainFrame.getInstance()); File selectedFile = jfc.getSelectedFile(); if (selectedFile == null) { throw new IOException("No file chosen."); } return selectedFile.getCanonicalPath() + File.separator + year + PDF_SUFFIX; } @Override public void initChart() { chart = ChartFactory.createBarChart3D("", getLang().getString("Month"), getLang().getString("Consumption"), consumption.generateYearDatasetForDiagram(), PlotOrientation.VERTICAL, true, true, true); } /** * Creates and saves the PDF to the destination. * @param destination The path to the destination. * @throws ExporterException Could not export data. */ @Override public void writeToFile(String destination) throws ExporterException { File exportFile = new File(destination); try { openFileToWrite(exportFile); writeDocument(); } catch (Exception e) { handleWriteException(e, exportFile); } } private void openFileToWrite(File exportFile) throws Exception { if (exportFile.exists()) { throw new ExporterException("Cannot overwrite file."); } PdfWriter.getInstance(document, new FileOutputStream(exportFile)); } private void writeDocument() throws Exception { document.open(); addHeading(); addDiagram(); addTable(); document.close(); } private void addHeading() throws Exception { Element elem = new Paragraph("Energieverbrauch " + year, new Font(Font.TIMES_ROMAN, 24)); document.add(elem); } private void addDiagram() throws Exception { if (chart != null) { File imgFile = new File(System.currentTimeMillis() + JPEG_SUFFIX); ChartUtilities.saveChartAsJPEG(imgFile, chart, 500, 300); Element elem = Image.getInstance(imgFile.getCanonicalPath()); document.add(elem); imgFile.delete(); } else { throw new ExporterException("Could not find diagram."); } } private void addTable() throws Exception { setupTable(); addTableHead(); addTableBody(); document.add(table); } private void setupTable() throws Exception { table = new Table(5); table.setPadding(2.0f); table.setWidth(100.0f); table.setSpacing(0.0f); } private void addTableHead() throws Exception { addTableHeadCell("Monat"); addTableHeadCell("Gas"); addTableHeadCell("Strom"); addTableHeadCell("Wasser"); addTableHeadCell("Kommentar"); } private void addTableHeadCell(String heading) throws Exception { Chunk chunk = new Chunk(heading, TABLE_HEAD_FONT); Cell cell = new Cell(chunk); table.addCell(cell); } private void addTableBody() throws Exception { DecimalFormat df = new DecimalFormat("#0.0"); for (Month month : Month.values()) { table.addCell(new Cell(month.toString())); table.addCell(new Cell(df.format(consumption.getConsumption(month, Resource.GAS)))); table.addCell(new Cell(df.format(consumption.getConsumption(month, Resource.POWER)))); table.addCell(new Cell(df.format(consumption.getConsumption(month, Resource.WATER)))); table.addCell(new Cell(counter.getComment(month))); } } private void handleWriteException(Exception e, File exportFile) throws ExporterException { long timeSinceLastChange = System.currentTimeMillis() - exportFile.lastModified(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Time since last change of export destination: " + timeSinceLastChange); } if (exportFile.exists() && timeSinceLastChange < EXPECTED_MAX_EXPORT_TIME) { exportFile.delete(); } throw new ExporterException("Could not export data.", e); } }