com.kovtun.WorkTimeMap.UI.TimeReport.java Source code

Java tutorial

Introduction

Here is the source code for com.kovtun.WorkTimeMap.UI.TimeReport.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.kovtun.WorkTimeMap.UI;

import com.kovtun.WorkTimeMap.Models.db.Action;
import com.kovtun.WorkTimeMap.Models.db.Project;
import com.kovtun.WorkTimeMap.Models.db.User;
import com.kovtun.WorkTimeMap.Models.other.ReportUser;
import com.kovtun.WorkTimeMap.Models.other.TimeTreeModel;
import com.kovtun.WorkTimeMap.Values;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 *
 * @author kovtun
 */
public class TimeReport extends javax.swing.JDialog {
    private Project project;
    private EntityManagerFactory emf;
    private EntityManager em;
    private List<ReportUser> users;

    /**
     * Creates new form TimeReport
     */
    public TimeReport(java.awt.Frame parent, boolean modal, Project project) {
        super(parent, modal);
        emf = Persistence.createEntityManagerFactory("Work_Time_MapPU");
        em = emf.createEntityManager();
        this.project = project;
        initComponents();
        ((JPanel) userForm1.getComponents()[2]).remove(((JPanel) userForm1.getComponents()[2]).getComponents()[2]);
        setTree(project);
    }

    public void setTree(Project project) {
        tree1.setModel(new TimeTreeModel(getData(project), project.getName()));

        tree1.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                if (e.getPath().getPathCount() == 3) {
                    Action action = ((Action) e.getPath().getPath()[2]);
                    setValuesToUI(action);
                }
            }
        });

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem1 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        tree1 = new javax.swing.JTree();
        userForm1 = new com.kovtun.WorkTimeMap.UI.UserForm();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setViewportView(tree1);

        jMenu1.setText("");

        jMenuItem2.setText(" Exel ");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setText("");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userForm1, javax.swing.GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1).addComponent(userForm1,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE))
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        try {
            writeExelFile();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, Values.IOException, "", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        dispose();
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void writeExelFile() throws IOException {
        String filePath = saveFileChooser();
        if (filePath != null) {
            if (filePath.indexOf(".xls") == -1) {
                filePath += ".xls";
            }
            generateData().write(new FileOutputStream(new File(filePath)));
        }
    }

    private String saveFileChooser() {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xls", "xls");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
            return chooser.getSelectedFile().getPath();
        return null;
    }

    private Workbook generateData() {
        Workbook book = new HSSFWorkbook();
        Sheet sheet = book.createSheet();
        int rowCount = 1;
        //? 
        Row projRow = sheet.createRow(0);
        Cell prjName = projRow.createCell(0);
        prjName.setCellValue(project.getName());

        for (ReportUser user : users) {
            //?
            Row row = sheet.createRow(rowCount);

            Cell nullCell = row.createCell(0);
            nullCell.setCellValue(" ");

            Row nameRow = sheet.createRow(rowCount);

            Cell nameCell = nameRow.createCell(0);
            nameCell.setCellValue(user.getFio());

            Cell userAllTimeCell = nameRow.createCell(1);
            userAllTimeCell.setCellValue((user.getAllTime() / (1000 * 60)) / 60 + " . "
                    + (user.getAllTime() / (1000 * 60) % 60 + " ."));

            //
            rowCount++;
            Row aRow = sheet.createRow(rowCount);

            Cell aNumber = aRow.createCell(0);
            aNumber.setCellValue("");

            Cell aName = aRow.createCell(1);
            aName.setCellValue("?");

            Cell aDescription = aRow.createCell(2);
            aDescription.setCellValue("?");

            Cell aComment = aRow.createCell(3);
            aComment.setCellValue("");

            Cell aDate = aRow.createCell(4);
            aDate.setCellValue(" ");

            Cell aTime = aRow.createCell(5);
            aTime.setCellValue("? ?");

            //   
            List<Action> list = user.getActions();
            int k = 1;
            for (Action action : list) {
                rowCount++;
                Row actionRow = sheet.createRow(rowCount);

                Cell actionNumber = actionRow.createCell(0);
                actionNumber.setCellValue(k);
                k++;

                Cell actionName = actionRow.createCell(1);
                actionName.setCellValue(action.getName());

                Cell actionDescription = actionRow.createCell(2);
                actionDescription.setCellValue(action.getDescription());

                Cell actionComment = actionRow.createCell(3);
                actionComment.setCellValue(action.getComment());

                Cell actionDate = actionRow.createCell(4);
                actionDate.setCellValue(action.getStringDate());

                Cell actionTime = actionRow.createCell(5);
                actionTime.setCellValue((action.getStopTime() == null ? "? !"
                        : ((action.getStopTime().getTime() - action.getStartTime().getTime()) / (1000 * 60)) / 60
                                + " . " + ((action.getStopTime().getTime() - action.getStartTime().getTime())
                                        / (1000 * 60) % 60 + " .")));

            }
            rowCount++;

        }

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(2);
        sheet.autoSizeColumn(3);
        sheet.autoSizeColumn(4);
        sheet.autoSizeColumn(5);

        return book;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree tree1;
    private com.kovtun.WorkTimeMap.UI.UserForm userForm1;
    // End of variables declaration//GEN-END:variables

    private List<ReportUser> getData(Project project) {
        users = new ArrayList();
        for (User u : project.getUserList()) {
            ReportUser ru = new ReportUser(u.getId(), u.getFio());
            ru.setActions(em.createNamedQuery("Action.findByUserIdAndProject", Action.class)
                    .setParameter("idu", u.getId()).setParameter("idp", project.getId()).getResultList());
            users.add(ru);
        }
        return users;
    }

    private void setValuesToUI(Action action) {
        userForm1.nameTextField.setText(action == null ? "" : action.getName());
        userForm1.descriptionArea.setText(action == null ? "" : action.getDescription());
        userForm1.CommentArea.setText(action == null ? "" : action.getComment());
        userForm1.startTimeLabel
                .setText(action == null ? "" : new SimpleDateFormat("HH:mm").format(action.getStartTime()));
        userForm1.stopTimeLabel.setText(action == null ? ""
                : action.getStopTime() != null ? new SimpleDateFormat("HH:mm").format(action.getStopTime())
                        : "  !");
        userForm1.projectLabel.setText(action == null ? "" : action.getProjectId().getName());
    }
}