vn.vnpttech.ssdc.nms.webapp.action.MatAction.java Source code

Java tutorial

Introduction

Here is the source code for vn.vnpttech.ssdc.nms.webapp.action.MatAction.java

Source

/*
 * Copyright 2016 Pivotal Software, Inc..
 *
 * 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 vn.vnpttech.ssdc.nms.webapp.action;

import static com.opensymphony.xwork2.Action.SUCCESS;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import vn.vnpttech.ssdc.nms.model.ActionTypeEnum;
import vn.vnpttech.ssdc.nms.model.Materials;
import vn.vnpttech.ssdc.nms.model.Materials;

/**
 *
 * @author longdq
 */
public class MatAction extends BaseAction {

    private File file;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    //Load Materials  with Criteria
    public InputStream getLoadMaterials() {
        try {
            HttpServletRequest request = getRequest();
            String matName = request.getParameter("matName");
            String unitStr = request.getParameter("unit");
            String unitPriceStr = request.getParameter("unitPrice");
            String weightStr = request.getParameter("weight");

            Double unit = null;
            if (StringUtils.isNotBlank(unitStr)) {
                unit = Double.parseDouble(unitStr);
            }

            Double unitPrice = null;
            if (StringUtils.isNotBlank(unitPriceStr)) {
                unitPrice = Double.parseDouble(unitPriceStr);
            }

            Double weight = null;
            if (StringUtils.isNotBlank(weightStr)) {
                weight = Double.parseDouble(weightStr);
            }

            Map pagingMap = materialsManager.searchMaterials(matName, unit, unitPrice, weight, start.intValue(),
                    limit.intValue());

            List<Materials> searchResult = new ArrayList<Materials>();
            JSONArray materialsList = new JSONArray();
            if (pagingMap != null && pagingMap.get("list") != null) {
                searchResult = (List<Materials>) pagingMap.get("list");
                for (Materials tmp : searchResult) {
                    JSONObject obj = new JSONObject();
                    //                    Map map = BeanUtils.describe(tmp);
                    //                    for (Object key : map.keySet()) {
                    //                        obj.put(key.toString(), map.get(key));
                    //                    }
                    obj.put("name", tmp.getName());
                    obj.put("id", tmp.getId());
                    obj.put("unit", tmp.getUnit());
                    obj.put("unitPrice", tmp.getUnitPrice());
                    obj.put("materialsWeight", tmp.getWeight());
                    materialsList.put(obj);
                }
            }
            Long count = 0L;
            if (pagingMap.get("totalCount") != null) {
                count = (Long) pagingMap.get("totalCount");
            }
            JSONObject result = new JSONObject();
            result.put("list", materialsList);
            result.put("totalCount", count);
            return new ByteArrayInputStream(result.toString().getBytes("UTF8"));
        } catch (Exception ex) {
            log.error("ERROR getLoadMaterials: ", ex);
            return null;
        }
    }//End

    //Delete Materials
    public InputStream getDeleteMaterials() {
        try {
            HttpServletRequest request = getRequest();
            String itemIdList = request.getParameter("itemIdList");
            JSONObject result = new JSONObject();
            String[] listId = itemIdList.split(",");
            for (String idTmp : listId) {
                materialsManager.remove(Integer.parseInt(idTmp));
            }
            result.put("deleteStatus", "success");
            return new ByteArrayInputStream(result.toString().getBytes("UTF8"));
        } catch (Exception ex) {
            log.error("Delete Materials failed: ", ex);
            return null;
        }
    }//End

    public InputStream getSaveMaterials() {
        try {
            HttpServletRequest request = getRequest();

            JSONObject result = new JSONObject();

            String id = request.getParameter("id");
            String matName = request.getParameter("matName");
            String unitStr = request.getParameter("unit");
            String unitPriceStr = request.getParameter("unitPrice");
            String weightStr = request.getParameter("weight");

            Double unit = null;
            if (StringUtils.isNotBlank(unitStr)) {
                unit = Double.parseDouble(unitStr);
            }

            Double unitPrice = null;
            if (StringUtils.isNotBlank(unitPriceStr)) {
                unitPrice = Double.parseDouble(unitPriceStr);
            }

            Double weight = null;
            if (StringUtils.isNotBlank(weightStr)) {
                weight = Double.parseDouble(weightStr);
            }

            Materials saveItem = new Materials();
            if (StringUtils.isNotBlank(id)) {
                Integer materialsId = Integer.parseInt(id);
                saveItem = materialsManager.get(materialsId);
            }

            saveItem.setName(matName);
            // saveItem.setUnit(unit);
            saveItem.setUnitPrice(unitPrice);
            saveItem.setWeight(weight);

            //            materialsManager.save(saveItem);
            boolean flag = false;
            if (StringUtils.isBlank(id)) {
                flag = materialsManager.checkExist(saveItem);
            }
            if (flag) {
                result.put("saveStatus", "success");
                result.put("errorMsg", "exist");
            } else {
                materialsManager.save(saveItem);
                result.put("saveStatus", "success");
                result.put("errorMsg", "ok");
            }

            //            result.put("saveStatus", "success");
            return new ByteArrayInputStream(result.toString().getBytes("UTF8"));
        } catch (Exception ex) {
            log.error("ERROR save Materials : ", ex);
            return null;
        }
    }//End

    public InputStream getUploadMat() {
        JSONObject result = new JSONObject();
        try {
            JSONArray array = new JSONArray();
            try {
                //Parse excel
                List<Materials> list = processExcelFile(file);
                //                List<Materials> listToBeSaved = new ArrayList<Materials>();
                //iterate through items
                int counter = 0;
                for (Materials item : list) {
                    if (!materialsManager.checkExist(item)) {
                        materialsManager.save(item);
                        counter++;
                    }
                }

                log.info(ActionTypeEnum.UPLOAD.getName() + " " + counter + "/" + list.size() + " items saved");

                result.put(SUCCESS, true);
                //                result.put("msg", "Upload successful!");
                //                List params = new ArrayList();
                //                params.add(" " + counter + "/" + list.size());
                //                log.debug(getText("filedupload.msg", params));
                //                log.debug("-------------------xin cho cc bn. y l ting vit");
                //                result.put("msg", getText("filedupload.msg", params));
                result.put("msg", " " + counter + "/" + list.size() + " ");
                result.put("file", file);

            } catch (Exception e) {
                result.put(SUCCESS, false);
                result.put("msg", getText("management.areaMapping.invalidFile"));
                log.error(e);
            }

        } catch (Exception e) {
            //e.printStackTrace();
            log.error(e);
            //return null;
        }

        return new ByteArrayInputStream(result.toString().getBytes());
    }// end---------------

    private List<Materials> processExcelFile(File file) throws IOException {
        List<Materials> list = new ArrayList<Materials>();

        //try {
        // Creating Input Stream
        FileInputStream myInput = new FileInputStream(file);

        // Create a workbook using the File System 
        XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);

        // Get the first sheet from workbook 
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);

        Materials item = new Materials();

        /**
         * We now need something to iterate through the cells.*
         */
        Iterator<Row> rowIter = mySheet.rowIterator();
        while (rowIter.hasNext()) {
            XSSFRow myRow = (XSSFRow) rowIter.next();
            if (myRow.getRowNum() != 0) {// loi b? header

                Iterator<Cell> cellIter = myRow.cellIterator();
                while (cellIter.hasNext()) {
                    XSSFCell myCell = (XSSFCell) cellIter.next();

                    if (myCell.getCellType() != HSSFCell.CELL_TYPE_STRING) {
                        myCell.setCellType(Cell.CELL_TYPE_STRING);
                    }
                    String value = myCell.getStringCellValue().trim();

                    switch (myCell.getColumnIndex()) {
                    case 0: //stt ko lam gi
                        //                        item.setProvince(value);
                        break;

                    case 1: //name
                        item.setName(value);
                        break;

                    //                        case 2: //unit
                    //                            if (StringUtils.isNotBlank(value)) {
                    //                                item.setUnit(Double.parseDouble(value));
                    //                            } else {
                    //                                item.setUnit(0);
                    //                            }
                    //                            break;
                    case 2: //unit price
                        if (StringUtils.isNotBlank(value)) {
                            item.setUnitPrice(Double.parseDouble(value));
                        } else {
                            item.setUnitPrice(0.0);
                        }
                        break;

                    case 3: //weight
                        if (StringUtils.isNotBlank(value)) {
                            item.setWeight(Double.parseDouble(value));
                        } else {
                            item.setWeight(0.0);
                        }
                        break;

                    default:
                        break;
                    }

                }
                list.add(item);

                if (item.getName() != null) {
                    item = new Materials(); //for next row
                }

            }
        }
        return list;
    }
}