com.itd.dbmrgdao.TestTime_newscanner.java Source code

Java tutorial

Introduction

Here is the source code for com.itd.dbmrgdao.TestTime_newscanner.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.itd.dbmrgdao;

import com.itd.common.dao.EmployeeDropDownDao;
import com.itd.common.dao.GennericDao;
import com.itd.regis.db.entity.ScanData;
import com.itd.regis.db.entity.ScanDataDate;
import com.itd.regis.db.entity.ScanDataKey;
import com.itd.regis.db.entity.ScanRule;
import com.itd.scan.dao.ScanDao;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Administrator Test if employee punch either time-in or timeout will
 * credit 8:00 and 17:00
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/config/BeanLocations.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional
public class TestTime_newscanner {

    @Autowired
    ScanDao scanDao;

    @Autowired
    GennericDao<ScanData> gennericDao;

    @Ignore
    @org.junit.Test
    public void test() throws ParseException {

        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
        chooser.setFileFilter(filter);
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();

        String fileName = f.getAbsolutePath();
        try {
            FileReader reader = new FileReader(fileName);
            BufferedReader br = new BufferedReader(reader);
            String strLine;

            Boolean result = updateScanFileRoundUp2(br);

            br.close();

        } catch (IOException ex) {

        }

    }

    private Boolean updateScanFileRoundUp2(BufferedReader br) {
        try {

            String strLine;

            SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");

            Calendar cal = Calendar.getInstance();

            ScanDataDate scanDataDateItem = null;

            Map<String, ScanDataDate> mapScanDatas = new HashMap<String, ScanDataDate>();

            String scode = "1985";

            //  ? ?? 
            String sunday2014 = "2557-01-05"; //default value for check correct setting year

            Date dateObj = curFormater.parse(sunday2014);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateObj);

            if (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                // system not correct   
                return false;
            }

            for (strLine = br.readLine(); strLine != null; strLine = br.readLine()) {

                String sysid = "", scdate = null, p1Start = null, p2End = null;
                Boolean isSunday = false;

                String parts[] = new String[7];
                // read data from scan machine by line
                parts[1] = strLine.substring(3, 11); // date
                parts[5] = strLine.substring(11, 15); // time
                parts[5] = new StringBuffer(parts[5]).insert(parts[5].length() - 2, ":").toString();
                parts[0] = strLine.substring(18, 27); // systemid

                // update read data to standard data
                sysid = parts[0];
                scdate = new StringBuffer(parts[1]).insert(parts[1].length() - 2, "-").toString();
                scdate = new StringBuffer(scdate).insert(scdate.length() - 5, "-").toString();

                // check if sunday must convert to 543 first
                String temp_scdate = (Integer.toString(Integer.parseInt(scdate.substring(0, 4)) + 543))
                        .concat(scdate.substring(4, 10));

                dateObj = curFormater.parse(temp_scdate);
                calendar = Calendar.getInstance();
                calendar.setTime(dateObj);

                if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                    isSunday = true;
                }

                // check time from scan machine for in or out
                ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);

                //if used in record
                if (mapScanDatas.containsKey(sysid)) {
                    scanDataDateItem = mapScanDatas.get(sysid);
                    mapScanDatas.remove(sysid);

                    p1Start = scanDataDateItem.getP1start();
                    p2End = scanDataDateItem.getP2end();
                } else {
                    // never used in record
                    scanDataDateItem = null;
                    p1Start = scanRule.getP1start();
                    p2End = scanRule.getP2end();
                }

                parts[6] = FindInOut(parts[5], scanRule.getP1break_st());

                if (parts[6].equals("01")) {
                    p1Start = CompareTime(p1Start, parts[5], "01");
                } else {
                    p2End = CompareTime(p2End, parts[5], "04");
                }

                // ?? ? ? table scan rule  code
                if (p2End == null || p2End.isEmpty()) {
                    //if not punch out Monthly or Daily will automatic p2End startdart time
                    p2End = scanRule.getP2end();
                } else {
                    p2End = CompareTime(p2End, scanRule.getP2end(), "04");

                    if (scanRule.getCalcot().equals("Y")) {
                        //check if 10 min roundup
                        // >= 50 will 60, < 50 and >= 20 will 30 , < 20 will be 00
                        p2End = MinRoundUp(p2End);

                    }
                }

                // ?
                if (isSunday) {
                    p2End = scanRule.getP2end();
                }

                scanDataDateItem = new ScanDataDate(sysid, scdate, scode, p1Start, p2End);
                mapScanDatas.put(sysid, scanDataDateItem);

                System.out.println("Sysid : " + sysid + ", In : " + scanDataDateItem.getP1start() + ", Out : "
                        + scanDataDateItem.getP2end());

            }

            // create SQL and update data in table
            UpdateScanData(mapScanDatas);

            br.close();
            return true;

        } catch (IOException | ParseException e) {
            JOptionPane.showMessageDialog(null, e);
        }
        return false;
    }

    private void UpdateScanData(Map mp) {

        StringBuilder deleteSQL = new StringBuilder("DELETE FROM scandata WHERE (sc_sysid,scdate) IN (");
        StringBuilder insertSQL = new StringBuilder(
                "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p2end) VALUES ");

        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            ScanDataDate item = (ScanDataDate) pairs.getValue();

            deleteSQL = deleteSQL.append(" ('").append(item.getSc_sysid()).append("','").append(item.getScdate())
                    .append("'),");

            insertSQL = insertSQL.append(" ('").append(item.getSc_sysid()).append("','").append(item.getSc_scode())
                    .append("','").append(item.getScdate()).append("','").append(item.getP1start()).append("','")
                    .append(item.getP2end()).append("'),");

            it.remove(); // avoids a ConcurrentModificationException
        }

        String result;
        // executeSQL delete scandata
        result = ReplaceRightString(deleteSQL.toString(), ",", ")");
        scanDao.executeSQL(result);

        // executeSQL insert scandata
        result = ReplaceRightString(insertSQL.toString(), ",", "");
        scanDao.executeSQL(result);

    }

    private String ReplaceRightString(String org, String search, String sub) {
        int i = org.lastIndexOf(search);
        String result = org.substring(0, i);
        result = result + sub;
        result = result + org.substring(i + search.length());
        return result;
    }

    private String MinRoundUp(String myTime) {

        try {
            SimpleDateFormat parser1 = new SimpleDateFormat("HH:mm");
            Date date1 = parser1.parse(myTime);

            String compareTime = myTime.substring(0, 2) + ":00";

            SimpleDateFormat parser2 = new SimpleDateFormat("HH:mm");
            Date date2 = parser2.parse(compareTime);

            long diffInMins = Math.abs(date1.getTime() - date2.getTime()) / 60000;

            long ONE_MINUTE_IN_MILLIS;

            Date afterAddingMins;

            if (diffInMins >= 50) {
                ONE_MINUTE_IN_MILLIS = 60000 * (60 - diffInMins);
            } else if (diffInMins >= 20) {
                ONE_MINUTE_IN_MILLIS = 60000 * (30 - diffInMins);
            } else {
                ONE_MINUTE_IN_MILLIS = 60000 * (-1 * diffInMins);
            }

            afterAddingMins = new Date(date1.getTime() + (ONE_MINUTE_IN_MILLIS));

            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

            return timeFormat.format(afterAddingMins);

        } catch (ParseException ex) {

        }

        return "";
    }

    String CompareTime(String a, String b, String operator) throws ParseException {

        if (a == null) {
            return b;
        }

        SimpleDateFormat parser1 = new SimpleDateFormat("HH:mm");
        Date x = parser1.parse(a);
        Date y = parser1.parse(b);

        try {
            // The Magic happens here i only get the Time out of the Date Object
            SimpleDateFormat parser2 = new SimpleDateFormat("HH:mm");
            x = parser2.parse(parser2.format(x));
            y = parser2.parse(parser2.format(y));

        } catch (ParseException ex) {
            System.err.println(ex);
        }

        switch (operator) {
        case "01":
            return ((x.compareTo(y) <= 0) ? a : b);
        case "04":
            return ((x.compareTo(y) >= 0) ? a : b);
        default:
            throw new IllegalArgumentException("Operator " + operator + " not fould in control!");
        }
    }

    String FindInOut(String a, String b) throws ParseException {

        //        if (a == null) {
        //            return b;
        //        }
        SimpleDateFormat parser1 = new SimpleDateFormat("HH:mm");
        Date x = parser1.parse(a);
        Date y = parser1.parse(b);

        try {
            // The Magic happens here i only get the Time out of the Date Object
            SimpleDateFormat parser2 = new SimpleDateFormat("HH:mm");
            x = parser2.parse(parser2.format(x));
            y = parser2.parse(parser2.format(y));

        } catch (ParseException ex) {
            System.err.println(ex);
        }

        return ((x.compareTo(y) <= 0) ? "01" : "04");

    }
}