Subversion Repositories SmartDukaan

Rev

Rev 1075 | Rev 3105 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.support.controllers;

import in.shop2020.model.v1.catalog.Warehouse;
import in.shop2020.thrift.clients.CatalogServiceClient;
import in.shop2020.thrift.clients.HelperServiceClient;
import in.shop2020.utils.LogisticsUser;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

/**
 * Allows executives of courier companies to login and download courier details
 * report which they then use to upload into their database.
 * 
 * @author Chandranshu
 * 
 */
public class CourierDetailsController implements ServletResponseAware,
                ServletRequestAware, ServletContextAware {
        private String id;
        private int daysToSubtract;
        
        //FIXME: Read this configuration from the config client
        private String courierDetailsPath = "/CourierDetailReports";
        
        private ServletContext context;
        private HttpServletRequest request;
        private HttpServletResponse response;
        private HttpSession session;

        public String index(){
                if(getSessionUserName()==null)
                        return "authfail";
                else
                        return "authsuccess";
        }
        
        // Handler for POST /courier-details
        public String create(){
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                try{
                        HelperServiceClient helperServiceClient = new HelperServiceClient();
                        in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
                        LogisticsUser user = client.authenticateLogisticsUser(username, password);
                        session.setAttribute("username", user.getUsername());
                        session.setAttribute("providerId", Long.valueOf(user.getProviderId()));
                }catch(Exception e){
                        e.printStackTrace();
                        return "authfail";
                }
                return "authsuccess";
        }
        
        // Handler for GET /courier-details/<warehouseId>
        public String show(){
                try {
                        long warehouseId = Long.parseLong(getId());
                        long providerId = ((Long)session.getAttribute("providerId")).longValue();
                        
                        System.out.println("Warehouse Id is:  " + warehouseId);
                        System.out.println("Provider Id is: " + providerId);
                        
                        response.setContentType("application/vnd.ms-excel");
                        
                        Calendar date = new GregorianCalendar();
                        date.add(Calendar.DAY_OF_MONTH, daysToSubtract);
                        int year = date.get(Calendar.YEAR);
                        int month = date.get(Calendar.MONTH) +1;
                        int day = date.get(Calendar.DAY_OF_MONTH);
                        String fileName = courierDetailsPath + "/courier-details-"+warehouseId+"-"+ providerId + "-"+year+"-"+ month+"-" + day +".xls";
                        response.setHeader("Content-disposition", "inline; filename=courier-details-"+warehouseId+"-"+ providerId + "-"+year+"-"+ month+"-" + day +".xls" );
                        
                        ServletOutputStream sos;
                        try {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                baos.write(getBytesFromFile(new File(fileName)));
                                sos = response.getOutputStream();
                                baos.writeTo(sos);
                                sos.flush();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }       
                        return "authsuccess";
                }catch(NumberFormatException nfe){
                        nfe.printStackTrace();
                }
                return "authfail";
        }
        
        public String dayBefore(){
                daysToSubtract = -2;
                return show();
        }
        
        public String yesterday(){
                daysToSubtract = -1;
                return show();
        }
        
        public String today(){
                daysToSubtract = 0;
                return show();
        }
        
        // Returns the contents of the file in a byte array.
        public static byte[] getBytesFromFile(File file) throws IOException {
            FileInputStream is = new FileInputStream(file);
            
            // Get the size of the file
            long length = file.length();

            // You cannot create an array using a long type.
            // It needs to be an int type.
            // Before converting to an int type, check
            // to ensure that file is not larger than Integer.MAX_VALUE.
            if (length > Integer.MAX_VALUE) {
                // File is too large
            }

            // Create the byte array to hold the data
            byte[] bytes = new byte[(int)length];

            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("Could not completely read file "+file.getName());
            }

            // Close the input stream and return bytes
            is.close();
            return bytes;
        }
        
        @Override
        public void setServletContext(ServletContext context) {
                this.context = context;
        }
        
        @Override
        public void setServletResponse(HttpServletResponse response) {
                this.response  = response;
        }

        @Override
        public void setServletRequest(HttpServletRequest request) {
                this.request = request;
                this.session = request.getSession();
        }

        public String getId(){
                return id;
        }
        
        public void setId(String id){
                this.id = id;
        }
        
        public String getSessionUserName(){
                return (String) session.getAttribute("username");
        }
        
        public Map<Long, String> getWarehouses(){
                Map<Long, String> warehouseMap = new HashMap<Long, String>();
                try{
                        CatalogServiceClient csc = new CatalogServiceClient();
                        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
                        List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
                        for(Warehouse warehouse : warehouses){
                                warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
                        }
                }catch(Exception e){
                        e.printStackTrace();
                }
                return warehouseMap;
        }

        public String getServletContextPath(){
                return context.getContextPath();
        }
}