Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
679 chandransh 1
package in.shop2020.support.controllers;
2
 
754 chandransh 3
import in.shop2020.model.v1.catalog.Warehouse;
3125 rajveer 4
import in.shop2020.thrift.clients.CatalogClient;
5
import in.shop2020.thrift.clients.HelperClient;
749 chandransh 6
import in.shop2020.utils.LogisticsUser;
679 chandransh 7
 
8
import java.io.ByteArrayOutputStream;
756 chandransh 9
import java.io.File;
10
import java.io.FileInputStream;
679 chandransh 11
import java.io.IOException;
12
import java.util.Calendar;
13
import java.util.GregorianCalendar;
754 chandransh 14
import java.util.HashMap;
15
import java.util.List;
16
import java.util.Map;
679 chandransh 17
 
1075 chandransh 18
import javax.servlet.ServletContext;
679 chandransh 19
import javax.servlet.ServletOutputStream;
20
import javax.servlet.http.HttpServletRequest;
21
import javax.servlet.http.HttpServletResponse;
749 chandransh 22
import javax.servlet.http.HttpSession;
679 chandransh 23
 
24
import org.apache.struts2.interceptor.ServletRequestAware;
25
import org.apache.struts2.interceptor.ServletResponseAware;
1075 chandransh 26
import org.apache.struts2.util.ServletContextAware;
3062 chandransh 27
import org.slf4j.Logger;
28
import org.slf4j.LoggerFactory;
679 chandransh 29
 
2904 chandransh 30
/**
31
 * Allows executives of courier companies to login and download courier details
32
 * report which they then use to upload into their database.
33
 * 
34
 * @author Chandranshu
35
 * 
36
 */
679 chandransh 37
public class CourierDetailsController implements ServletResponseAware,
1075 chandransh 38
		ServletRequestAware, ServletContextAware {
3062 chandransh 39
 
40
    private static Logger logger = LoggerFactory.getLogger(CourierDetailsController.class);
41
 
749 chandransh 42
	private String id;
1075 chandransh 43
	private int daysToSubtract;
756 chandransh 44
 
45
	//FIXME: Read this configuration from the config client
46
	private String courierDetailsPath = "/CourierDetailReports";
47
 
1075 chandransh 48
	private ServletContext context;
679 chandransh 49
	private HttpServletRequest request;
50
	private HttpServletResponse response;
749 chandransh 51
	private HttpSession session;
679 chandransh 52
 
749 chandransh 53
	public String index(){
54
		if(getSessionUserName()==null)
55
			return "authfail";
56
		else
57
			return "authsuccess";
58
	}
59
 
60
	// Handler for POST /courier-details
61
	public String create(){
62
		String username = request.getParameter("username");
63
		String password = request.getParameter("password");
64
		try{
3125 rajveer 65
			HelperClient helperServiceClient = new HelperClient();
749 chandransh 66
			in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
67
			LogisticsUser user = client.authenticateLogisticsUser(username, password);
68
			session.setAttribute("username", user.getUsername());
69
			session.setAttribute("providerId", Long.valueOf(user.getProviderId()));
70
		}catch(Exception e){
3105 chandransh 71
			logger.error("Error authenticating the user " + username, e);
749 chandransh 72
			return "authfail";
73
		}
74
		return "authsuccess";
679 chandransh 75
	}
76
 
749 chandransh 77
	// Handler for GET /courier-details/<warehouseId>
78
	public String show(){
79
		try {
80
			long warehouseId = Long.parseLong(getId());
81
			long providerId = ((Long)session.getAttribute("providerId")).longValue();
3062 chandransh 82
			boolean isCod;
83
			try {
84
	            isCod = Boolean.parseBoolean(request.getParameter("isCod"));
85
	        } catch (Exception e) {
86
	            isCod = false;
87
	        }
3105 chandransh 88
			logger.info("Download request for " + (isCod ? "COD" : "Prepaid") + " Courier Details report of warehouse Id: " + warehouseId + " and provider Id:" + providerId);
749 chandransh 89
 
3062 chandransh 90
			String deliveryType = "prepaid";
91
			if(isCod)
92
			    deliveryType = "cod";
93
 
749 chandransh 94
			response.setContentType("application/vnd.ms-excel");
95
 
96
			Calendar date = new GregorianCalendar();
1075 chandransh 97
			date.add(Calendar.DAY_OF_MONTH, daysToSubtract);
749 chandransh 98
			int year = date.get(Calendar.YEAR);
99
			int month = date.get(Calendar.MONTH) +1;
100
			int day = date.get(Calendar.DAY_OF_MONTH);
3062 chandransh 101
			String fileName = courierDetailsPath + "/courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-" + month + "-" + day +".xls";
102
			response.setHeader("Content-disposition", "inline; filename=courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-"+ month + "-" + day +".xls" );
749 chandransh 103
 
104
			ServletOutputStream sos;
105
			try {
756 chandransh 106
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
107
				baos.write(getBytesFromFile(new File(fileName)));
749 chandransh 108
				sos = response.getOutputStream();
109
				baos.writeTo(sos);
110
				sos.flush();
111
			} catch (IOException e) {
3062 chandransh 112
				logger.error("Unable to stream the courier details report", e);
749 chandransh 113
			}	
114
			return "authsuccess";
115
		}catch(NumberFormatException nfe){
3062 chandransh 116
			logger.error("Unable to parse the warehouse id", nfe);
749 chandransh 117
		}
118
		return "authfail";
119
	}
3105 chandransh 120
 
121
    /**
122
     * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
123
     * Should be used to view day before yesterday's courier details report.
124
     * 
125
     * @return the same string tokens as show
126
     */
1075 chandransh 127
	public String dayBefore(){
128
		daysToSubtract = -2;
129
		return show();
130
	}
3105 chandransh 131
 
132
    /**
133
     * Sets the daysToSubtract to -1 and then invokes the standard show()
134
     * handler. Should be used to view yesterday's courier details report.
135
     * 
136
     * @return the same string tokens as show
137
     */
1075 chandransh 138
	public String yesterday(){
139
		daysToSubtract = -1;
140
		return show();
141
	}
3105 chandransh 142
 
143
    /**
144
     * Sets the daysToSubtract to 0 and then invokes the standard show()
145
     * handler. Should be used to view today's courier details report.
146
     * 
147
     * @return the same string tokens as show
148
     */
1075 chandransh 149
	public String today(){
150
		daysToSubtract = 0;
151
		return show();
152
	}
153
 
3105 chandransh 154
    /**
155
     * Reads a file and converts its contents to a byte array.
156
     * 
157
     * @param file
158
     *            Name of the file to process
159
     * @return the contents of the file in a byte array.
160
     * @throws IOException
161
     *             if the file could not be found or read or is too big to
162
     *             convert to a byte array.
163
     */
164
	private static byte[] getBytesFromFile(File file) throws IOException {
756 chandransh 165
	    FileInputStream is = new FileInputStream(file);
166
 
167
	    // Get the size of the file
168
	    long length = file.length();
169
 
170
	    // You cannot create an array using a long type.
171
	    // It needs to be an int type.
172
	    // Before converting to an int type, check
173
	    // to ensure that file is not larger than Integer.MAX_VALUE.
174
	    if (length > Integer.MAX_VALUE) {
175
	        // File is too large
3105 chandransh 176
	        throw new IOException(file.getName() + " is too large to stream");
756 chandransh 177
	    }
178
 
179
	    // Create the byte array to hold the data
180
	    byte[] bytes = new byte[(int)length];
181
 
182
	    // Read in the bytes
183
	    int offset = 0;
184
	    int numRead = 0;
185
	    while (offset < bytes.length
186
	           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
187
	        offset += numRead;
188
	    }
189
 
190
	    // Ensure all the bytes have been read in
191
	    if (offset < bytes.length) {
192
	        throw new IOException("Could not completely read file "+file.getName());
193
	    }
194
 
195
	    // Close the input stream and return bytes
196
	    is.close();
197
	    return bytes;
198
	}
199
 
679 chandransh 200
	@Override
1075 chandransh 201
	public void setServletContext(ServletContext context) {
202
		this.context = context;
203
	}
204
 
205
	@Override
679 chandransh 206
	public void setServletResponse(HttpServletResponse response) {
207
		this.response  = response;
208
	}
209
 
210
	@Override
211
	public void setServletRequest(HttpServletRequest request) {
212
		this.request = request;
749 chandransh 213
		this.session = request.getSession();
679 chandransh 214
	}
215
 
749 chandransh 216
	public String getId(){
217
		return id;
218
	}
219
 
220
	public void setId(String id){
221
		this.id = id;
222
	}
223
 
224
	public String getSessionUserName(){
225
		return (String) session.getAttribute("username");
226
	}
3105 chandransh 227
 
228
    /**
229
     * Gets the list of all warehouses and maps the warehouse ids to their
230
     * display name.
231
     * 
232
     * @return the mapping of warehouse if to its display namee
233
     */
754 chandransh 234
	public Map<Long, String> getWarehouses(){
235
		Map<Long, String> warehouseMap = new HashMap<Long, String>();
236
		try{
3125 rajveer 237
			CatalogClient csc = new CatalogClient();
754 chandransh 238
			in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
239
			List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
240
			for(Warehouse warehouse : warehouses){
241
				warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
242
			}
243
		}catch(Exception e){
3105 chandransh 244
			logger.error("Error getting the list of warehouses", e);
754 chandransh 245
		}
246
		return warehouseMap;
247
	}
749 chandransh 248
 
1075 chandransh 249
	public String getServletContextPath(){
250
		return context.getContextPath();
251
	}
679 chandransh 252
}