Subversion Repositories SmartDukaan

Rev

Rev 6034 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.support.controllers;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
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;
import org.apache.struts2.dispatcher.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author mandeep
 * 
 */
public class FileArchiveController extends ActionSupport {
    /**
     * 
     */
    private static final String ARCHIVE_DIR = "/InventoryReports/";
    private static Logger logger = LoggerFactory.getLogger(FileArchiveController.class);
    
    private static enum FILE_TYPES {
        SARVOTTAM_INVENTORY_TSV_FILE(2, 175),
        SNCA_INVENTORY_XML_FILE(1, 193);

        int type;
        long warehouseId;

        FILE_TYPES(int type, long warehouseId) {
            this.type = type;
            this.warehouseId = warehouseId;
        }

        int getType() {
            return type;
        }
        
        long getWarehouseId() {
            return warehouseId;
        }
    };

    private File file;
    private int fileType;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");

    public StreamResult create() {
        try {
            logger.info("Trying to archive file with type: " + fileType);
            File newFile = new File(ARCHIVE_DIR + fileType + "-"
                    + sdf.format(new Date()) + ".xls");
            FileUtils.copyFile(file, newFile);

            // For Sarvottam, convert to xls
            if (fileType == FILE_TYPES.SARVOTTAM_INVENTORY_TSV_FILE.getType()) {
                File file = new File(convertToXls(newFile));
                uploadInventoryFile(file, FILE_TYPES.SARVOTTAM_INVENTORY_TSV_FILE.getWarehouseId());
            }
            else if(fileType == FILE_TYPES.SNCA_INVENTORY_XML_FILE.getType()) {
                File file = new File(convertXmlToXls(newFile));
                uploadInventoryFile(file, FILE_TYPES.SNCA_INVENTORY_XML_FILE.getWarehouseId());
            }

            return new StreamResult(new ByteArrayInputStream(
                    ("File uploaded successfully at " + sdf.format(new Date()))
                            .getBytes()));

        } catch (IOException e) {
            logger.error("Error archiving file", e);
            return new StreamResult(new ByteArrayInputStream(
                    ("Could not upload file at " + sdf.format(new Date()))
                            .getBytes()));
        }
    }

    /**
     * @param file
     */
    private void uploadInventoryFile(File file, long warehouseId) {
        try {
            String inventoryUploadUrl = "http://localhost:8080/inventory/supplier-inventory";
            HttpPost inventoryUploadPost = new HttpPost(inventoryUploadUrl);
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("warehouseId", new StringBody(String.valueOf(warehouseId)));
            entity.addPart("file", new FileBody(file));
            inventoryUploadPost.setEntity(entity);

            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(inventoryUploadPost);
            byte[] b = new byte[1000];
            response.getEntity().getContent().read(b);
            System.out.println(new String(b));
            logger.info("Response: " + new String(b));
        } catch (Exception e) {
            logger.error("Could not upload inventory: " + e);
        }
    }

    /**
     * @param tsvFile
     */
    private String convertToXls(File tsvFile) {
        try {
            Workbook w = new HSSFWorkbook();
            String convertedFileName = ARCHIVE_DIR + "Converted-"
                    + tsvFile.getName();
            FileOutputStream fileOut = new FileOutputStream(convertedFileName);
            Sheet sheet = w.createSheet();
            BufferedReader br = new BufferedReader(new FileReader(tsvFile));
            String line = br.readLine();
            int i = 0;
            while (line != null) {
                Row row = sheet.createRow(i++);
                int j = 0;
                for (String s : line.split("\t")) {
                    Cell cell = row.createCell(j++);
                    System.out.println("Writing: " + s);
                    cell.setCellValue(s);
                }
                line = br.readLine();
            }
            w.write(fileOut);
            return convertedFileName;
        } catch (Exception e) {
            logger.error("Error converting file", e);
            return tsvFile.getName();
        }
    }

    /**
    * @param xmlFile
    */
   private String convertXmlToXls(File xmlFile) {
       try {
           String xmlData = correctMalformedTags(xmlFile); 
           
           Workbook w = new HSSFWorkbook();
           Sheet sheet=w.createSheet("spreadSheet");
           String convertedFileName = ARCHIVE_DIR + "Converted-"
                   + xmlFile.getName();
           FileOutputStream fileOut = new FileOutputStream(convertedFileName);
           DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = factory.newDocumentBuilder();
           InputSource is = new InputSource(new StringReader(xmlData));
           org.w3c.dom.Document document = builder.parse(is);
           
           NodeList itemNameList = document.getElementsByTagName("DSPDISPNAME");
           NodeList itemQtyList = document.getElementsByTagName("DSPCLQTY");
           
           for(int i =1; i<=itemNameList.getLength(); i++) {
                   Row row = sheet.createRow(i);
                   int j = 0;
                   Cell cell1 = row.createCell(j++);
                   cell1.setCellValue(i);
                   Cell cell2 = row.createCell(j++);
                   cell2.setCellValue(itemNameList.item(i-1).getFirstChild().getNodeValue());
                   Cell cell3 = row.createCell(j++);
                   cell3.setCellValue(itemQtyList.item(i-1).getFirstChild().getNodeValue());
           }
           
           w.write(fileOut);
           return convertedFileName;
       } catch (Exception e) {
           logger.error("Error converting file", e);
           return xmlFile.getName();
       }
   }
    
    private String correctMalformedTags(File xmlFile) throws IOException {
        String xmlContent = readFileAsString(xmlFile);
        xmlContent = xmlContent.replace("<DSPACCNA\\nE>", "<DSPACCNAME>").
                replace("<DSPACCNA\nE>", "<DSPACCNAME>").replace("<\\nSPACCNAME>", "<DSPACCNAME>").
                replace("<\nSPACCNAME>", "<DSPACCNAME>").replace("<D\\nPACCNAME>", "<DSPACCNAME>").
                replace("<D\nPACCNAME>", "<DSPACCNAME>").replace("<DS\\nACCNAME>", "<DSPACCNAME>").
                replace("<DS\nACCNAME>", "<DSPACCNAME>").replace("<DSP\\nCCNAME>", "<DSPACCNAME>").
                replace("<DSP\nCCNAME>", "<DSPACCNAME>").replace("<DSPA\\nCNAME>", "<DSPACCNAME>").
                replace("<DSPA\nCNAME>", "<DSPACCNAME>").replace("<DSPAC\\nNAME>", "<DSPACCNAME>").
                replace("<DSPAC\nNAME>", "<DSPACCNAME>").replace("<DSPACC\\nAME>", "<DSPACCNAME>").
                replace("<DSPACC\nAME>", "<DSPACCNAME>").replace("<DSPACCN\\nME>", "<DSPACCNAME>").
                replace("<DSPACCN\nME>", "<DSPACCNAME>").replace("<DSPACCNA\\nE>", "<DSPACCNAME>").
                replace("<DSPACCNA\nE>", "<DSPACCNAME>").replace("<DSPACCNAM\\n>", "<DSPACCNAME>").
                replace("<DSPACCNAM\n>", "<DSPACCNAME>").replace("DSPACCNAME\\n<", "DSPACCNAME><").
                replace("DSPACCNAME\n<", "DSPACCNAME><").replace("DSPACCNAME\\n <", "DSPACCNAME><").
                replace("DSPACCNAME\n <", "DSPACCNAME><");
        System.out.println(xmlContent);
        return xmlContent;
        }

    private static String readFileAsString(File file)
        throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(
                        new FileReader(file));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }
    
        public File getFile() {
        return file;
    }

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

    public int getFileType() {
        return fileType;
    }

    public void setFileType(int fileType) {
        this.fileType = fileType;
    }

    public static void main(String[] args) {
        FileArchiveController arch = new FileArchiveController();
        arch.file = new File("/InventoryReports/1-2012-09-21-17:00:06.xls");
        arch.fileType = 1;
        arch.create();
        //new FileArchiveController().uploadInventoryFile(file, 193);
        System.out.println("done");
    }
}