Reporting Functionality - added HTML export
[habeas.git] / src / habeas / NoticesReportViewDialog.java
1 /*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package habeas;
7
8 import java.awt.Component;
9 import java.util.ArrayList;
10 import javax.swing.JFileChooser;
11 import javax.swing.JOptionPane;
12 import javax.swing.JTable;
13 import javax.swing.filechooser.FileFilter;
14 import javax.swing.filechooser.FileNameExtensionFilter;
15 import javax.swing.table.DefaultTableModel;
16 import javax.swing.table.TableCellRenderer;
17 import javax.swing.table.TableColumn;
18 import javax.swing.table.TableColumnModel;
19
20 /**
21 *
22 * @author hari
23 */
24 public class NoticesReportViewDialog extends javax.swing.JDialog {
25
26 private int currentReport;
27 private String reportTitle;
28 private String[] reportCols;
29 private ArrayList<Object> reportData;
30
31 /**
32 * Creates new form NoticesReportViewDialog
33 */
34 public NoticesReportViewDialog(java.awt.Frame parent, boolean modal) {
35 super(parent, modal);
36 initComponents();
37 populateClients ();
38 }
39
40 /**
41 * This method is called from within the constructor to initialize the form.
42 * WARNING: Do NOT modify this code. The content of this method is always
43 * regenerated by the Form Editor.
44 */
45 @SuppressWarnings("unchecked")
46 // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
47 private void initComponents() {
48
49 popMenu = new javax.swing.JPopupMenu();
50 menuExportCSV = new javax.swing.JMenuItem();
51 menuExportHTML = new javax.swing.JMenuItem();
52 labelReportTitle = new javax.swing.JLabel();
53 jScrollPane2 = new javax.swing.JScrollPane();
54 tableReport = new javax.swing.JTable();
55 checkFilterByClient = new javax.swing.JCheckBox();
56 comboClients = new javax.swing.JComboBox<>();
57 buttonApply = new javax.swing.JButton();
58
59 popMenu.setLabel("Popup");
60
61 menuExportCSV.setMnemonic('C');
62 menuExportCSV.setText("Export as CSV...");
63 menuExportCSV.addActionListener(new java.awt.event.ActionListener() {
64 public void actionPerformed(java.awt.event.ActionEvent evt) {
65 menuExportCSVActionPerformed(evt);
66 }
67 });
68 popMenu.add(menuExportCSV);
69
70 menuExportHTML.setMnemonic('H');
71 menuExportHTML.setText("Export as HTML...");
72 menuExportHTML.addActionListener(new java.awt.event.ActionListener() {
73 public void actionPerformed(java.awt.event.ActionEvent evt) {
74 menuExportHTMLActionPerformed(evt);
75 }
76 });
77 popMenu.add(menuExportHTML);
78
79 setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
80 setTitle("View Report");
81 setLocationByPlatform(true);
82
83 labelReportTitle.setFont(new java.awt.Font("Noto Sans", 1, 15)); // NOI18N
84 labelReportTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
85 labelReportTitle.setText("REPORT TITLE");
86
87 tableReport.setModel(new javax.swing.table.DefaultTableModel(
88 new Object [][] {
89
90 },
91 new String [] {
92
93 }
94 ));
95 tableReport.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
96 tableReport.setCellSelectionEnabled(true);
97 tableReport.setComponentPopupMenu(popMenu);
98 jScrollPane2.setViewportView(tableReport);
99
100 checkFilterByClient.setText("Filter by Client");
101
102 buttonApply.setMnemonic('a');
103 buttonApply.setText("Apply");
104 buttonApply.setToolTipText("");
105 buttonApply.addActionListener(new java.awt.event.ActionListener() {
106 public void actionPerformed(java.awt.event.ActionEvent evt) {
107 buttonApplyActionPerformed(evt);
108 }
109 });
110
111 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
112 getContentPane().setLayout(layout);
113 layout.setHorizontalGroup(
114 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
115 .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 679, Short.MAX_VALUE)
116 .addGroup(layout.createSequentialGroup()
117 .addComponent(labelReportTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
118 .addContainerGap())
119 .addGroup(layout.createSequentialGroup()
120 .addContainerGap()
121 .addComponent(checkFilterByClient, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
122 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
123 .addComponent(comboClients, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
124 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
125 .addComponent(buttonApply, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
126 );
127 layout.setVerticalGroup(
128 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
129 .addGroup(layout.createSequentialGroup()
130 .addComponent(labelReportTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
131 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
132 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
133 .addComponent(checkFilterByClient)
134 .addComponent(comboClients, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
135 .addComponent(buttonApply))
136 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
137 .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE))
138 );
139
140 pack();
141 }// </editor-fold>//GEN-END:initComponents
142
143 private void menuExportCSVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuExportCSVActionPerformed
144 // TODO add your handling code here:
145 JFileChooser chooser = new JFileChooser ();
146 FileFilter filter = new FileNameExtensionFilter("Comma Separated Values (.csv)", "csv");
147 chooser.setFileFilter(filter);
148 int rt = chooser.showSaveDialog(this);
149 if (rt == JFileChooser.APPROVE_OPTION) {
150 String filePath = chooser.getSelectedFile().getAbsolutePath();
151 if (!filePath.endsWith(".csv"))
152 filePath = filePath.concat(".csv");
153 boolean ret = Utility.saveReportCSV (filePath, reportCols, reportData);
154 if (ret == false)
155 JOptionPane.showMessageDialog(this, ERROR_SAVING_REPORT);
156 else
157 JOptionPane.showMessageDialog(this, REPORT_SAVED_SUCCESSFULLY);
158 }
159 }//GEN-LAST:event_menuExportCSVActionPerformed
160
161 private void buttonApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonApplyActionPerformed
162 // TODO add your handling code here:
163 if (! checkFilterByClient.isSelected()) {
164 reportData = Utility.getReportData(currentReport, -1);
165
166 if (reportData != null)
167 populateReport();
168 } else {
169 DBItem db = (DBItem)comboClients.getSelectedItem();
170 if (db == null)
171 return;
172 int selid = db.getKey();
173 reportData = Utility.getReportData(currentReport, selid);
174 if (reportData != null)
175 populateReport();
176 }
177
178 }//GEN-LAST:event_buttonApplyActionPerformed
179
180 private void menuExportHTMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuExportHTMLActionPerformed
181 // TODO add your handling code here:
182 JFileChooser chooser = new JFileChooser ();
183 FileNameExtensionFilter flt = new FileNameExtensionFilter("Hypertext Markup File (.html)", "html");
184 chooser.setFileFilter(flt);
185 int rt = chooser.showSaveDialog(this);
186 if (rt == JFileChooser.APPROVE_OPTION) {
187 String filepath = chooser.getSelectedFile().getAbsolutePath();
188 if (! (filepath.endsWith(".html") || filepath.endsWith(".htm")) )
189 filepath = filepath.concat(".html");
190 boolean ret= Utility.saveReportHTML (filepath, reportTitle, reportCols, reportData);
191 if (ret == false)
192 JOptionPane.showMessageDialog (this, ERROR_SAVING_REPORT);
193 else
194 JOptionPane.showMessageDialog(this, REPORT_SAVED_SUCCESSFULLY);
195
196 }
197 }//GEN-LAST:event_menuExportHTMLActionPerformed
198 private static final String REPORT_SAVED_SUCCESSFULLY = "Report saved successfully";
199 private static final String ERROR_SAVING_REPORT = "Error saving report";
200
201 /**
202 * @param args the command line arguments
203 */
204 public static void main(String args[]) {
205 /* Set the Nimbus look and feel */
206 //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
207 /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
208 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
209 */
210 try {
211 for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
212 if ("Nimbus".equals(info.getName())) {
213 javax.swing.UIManager.setLookAndFeel(info.getClassName());
214 break;
215 }
216 }
217 } catch (ClassNotFoundException ex) {
218 java.util.logging.Logger.getLogger(NoticesReportViewDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
219 } catch (InstantiationException ex) {
220 java.util.logging.Logger.getLogger(NoticesReportViewDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
221 } catch (IllegalAccessException ex) {
222 java.util.logging.Logger.getLogger(NoticesReportViewDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
223 } catch (javax.swing.UnsupportedLookAndFeelException ex) {
224 java.util.logging.Logger.getLogger(NoticesReportViewDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
225 }
226 //</editor-fold>
227
228 /* Create and display the dialog */
229 java.awt.EventQueue.invokeLater(new Runnable() {
230 public void run() {
231 NoticesReportViewDialog dialog = new NoticesReportViewDialog(new javax.swing.JFrame(), true);
232 dialog.addWindowListener(new java.awt.event.WindowAdapter() {
233 @Override
234 public void windowClosing(java.awt.event.WindowEvent e) {
235 System.exit(0);
236 }
237 });
238 dialog.setVisible(true);
239 }
240 });
241 }
242
243 // Variables declaration - do not modify//GEN-BEGIN:variables
244 private javax.swing.JButton buttonApply;
245 private javax.swing.JCheckBox checkFilterByClient;
246 private javax.swing.JComboBox<DBItem> comboClients;
247 private javax.swing.JScrollPane jScrollPane2;
248 private javax.swing.JLabel labelReportTitle;
249 private javax.swing.JMenuItem menuExportCSV;
250 private javax.swing.JMenuItem menuExportHTML;
251 private javax.swing.JPopupMenu popMenu;
252 private javax.swing.JTable tableReport;
253 // End of variables declaration//GEN-END:variables
254
255 public void setupReportTable(int reportNum, String title, String[] columns,
256 ArrayList<Object> data) {
257 currentReport = reportNum;
258 reportTitle = title;
259 reportCols = columns;
260 reportData = data;
261 DefaultTableModel mdl = new DefaultTableModel (columns, 0) {
262 @Override
263 public boolean isCellEditable (int row, int col) {
264 return false;
265 }
266 };
267 tableReport.setModel(mdl);
268
269 labelReportTitle.setText(title);
270 populateReport ();
271 }
272
273 private void populateReport () {
274 DefaultTableModel mdl = (DefaultTableModel)tableReport.getModel();
275 mdl.setRowCount(0);
276 for (int i = 0; i < reportData.size(); i += reportCols.length) {
277 Object[] row = new Object[reportCols.length];
278 for (int j = 0; j < reportCols.length; j ++)
279 row[j] = reportData.get(i+j);
280 mdl.addRow (row);
281 }
282 // resize the column widths to content size
283 for (int i = 0; i < tableReport.getColumnCount(); i ++) {
284
285 TableColumn clm = tableReport.getColumnModel().getColumn (i);
286 int preferredWidth = clm.getMinWidth()+10;
287 int maxWidth = 300;
288 int minWidth = 100;
289 for (int r = 0; r < tableReport.getRowCount(); r ++) {
290 TableCellRenderer rend = tableReport.getCellRenderer(r, i);
291 Component c = tableReport.prepareRenderer(rend, r, i);
292 int width = c.getPreferredSize().width + tableReport.getIntercellSpacing().width;
293 preferredWidth = Math.max (preferredWidth, width+10);
294 if (preferredWidth >= maxWidth)
295 {
296 preferredWidth = maxWidth;
297 break;
298 }
299 }
300 clm.setPreferredWidth(Math.max(minWidth, preferredWidth));
301 }
302 }
303
304 private void populateClients() {
305 ArrayList<Object> clients = Utility.getClientsNameAndId();
306 if (clients == null) return;
307 for (int i = 0; i < clients.size(); i += 2) {
308 comboClients.addItem (new DBItem ((int)clients.get(i),
309 (String)clients.get(i+1)));
310 }
311 }
312 }