Subversion Repositories SmartDukaan

Rev

Rev 5530 | Rev 6030 | Go to most recent revision | 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.text.SimpleDateFormat;
import java.util.Date;

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 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_XLS_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());
            }

            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();
        }
    }

    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) {
        File file = new File("/home/mandeep/2-2012-08-11-14:58:00.xls");
        new FileArchiveController().uploadInventoryFile(file, 175);
        System.out.println("done");
    }
}