Rev 5328 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.support.services;import in.shop2020.model.v1.catalog.CatalogServiceException;import in.shop2020.model.v1.catalog.Item;import in.shop2020.model.v1.order.LineItem;import in.shop2020.model.v1.order.Order;import in.shop2020.model.v1.order.Transaction;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.model.v1.user.Address;import in.shop2020.model.v1.user.Cart;import in.shop2020.model.v1.user.Line;import in.shop2020.model.v1.user.ShoppingCartException;import in.shop2020.model.v1.user.User;import in.shop2020.model.v1.user.UserContextException;import in.shop2020.model.v1.user.UserType;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.thrift.clients.UserClient;import java.io.ByteArrayOutputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Font;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.thrift.TException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class AnalysisDataGenerator {private static Logger logger = LoggerFactory.getLogger(AnalysisDataGenerator.class);UserClient usc;in.shop2020.model.v1.user.UserContextService.Client uClient;CatalogClient csc;in.shop2020.model.v1.catalog.CatalogService.Client cClient;TransactionClient tsc;in.shop2020.model.v1.order.TransactionService.Client tClient;public AnalysisDataGenerator() {try {usc = new UserClient();uClient = usc.getClient();csc = new CatalogClient();cClient = csc.getClient();tsc = new TransactionClient();tClient = tsc.getClient();} catch (Exception e) {logger.error("Unable to initialize connection with one of user, catalog or txn client", e);}}public ByteArrayOutputStream generateAnalysisReport(long startDate, long endDate) throws ShoppingCartException {List<User> users = null;try {users = uClient.getAllUsers(UserType.USER, startDate, endDate);} catch (TException e) {logger.error("Unable to get all users", e);}if (users == null || users.isEmpty()) {return null;}// Preparing XLS file for outputreturn getSpreadSheetData(users);}// Prepares the XLS worksheet object and fills in the data with proper// formattingprivate ByteArrayOutputStream getSpreadSheetData(List<User> users) {ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();Workbook wb = new HSSFWorkbook();Font font = wb.createFont();font.setBoldweight(Font.BOLDWEIGHT_BOLD);CellStyle style = wb.createCellStyle();style.setFont(font);CellStyle styleWT = wb.createCellStyle();styleWT.setWrapText(true);styleWT.setFillBackgroundColor((short)1);CellStyle styleUser = wb.createCellStyle();styleUser.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);CellStyle styleItem = wb.createCellStyle();styleItem.setFillBackgroundColor(HSSFColor.LIGHT_ORANGE.index);CellStyle styleOrder = wb.createCellStyle();styleOrder.setFillBackgroundColor(HSSFFont.COLOR_RED);styleOrder.setHidden(true);Sheet analysisSheet = wb.createSheet("User");short rowNo = 0;Row titleRow = analysisSheet.createRow(rowNo++);Cell titleCell = titleRow.createCell(0);titleCell.setCellValue("User Details");titleCell.setCellStyle(style);analysisSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));Row headerRow = analysisSheet.createRow(rowNo++);headerRow.createCell(0).setCellValue("S.No.");headerRow.createCell(1).setCellValue("User Id");headerRow.createCell(2).setCellValue("Email");headerRow.createCell(3).setCellValue("Name");headerRow.createCell(4).setCellValue("Communication Email");headerRow.createCell(5).setCellValue("Date of Birth");headerRow.createCell(6).setCellValue("Sex");headerRow.createCell(7).setCellValue("Mobile");headerRow.createCell(8).setCellValue("Registered On");headerRow.createCell(9).setCellValue("Last Login");headerRow.createCell(10).setCellValue("Cart Id");headerRow.createCell(11).setCellValue("Cart/Default Address");headerRow.createCell(12).setCellValue("Item Id");headerRow.createCell(13).setCellValue("Brand");headerRow.createCell(14).setCellValue("Model Name");headerRow.createCell(15).setCellValue("Model Number");headerRow.createCell(16).setCellValue("Order Id");headerRow.createCell(17).setCellValue("Order Status");headerRow.createCell(18).setCellValue("Status Description");headerRow.createCell(19).setCellValue("Order Amount");headerRow.createCell(20).setCellValue("Item Brand");headerRow.createCell(21).setCellValue("Model Name");headerRow.createCell(22).setCellValue("Model Number");Calendar calendar = Calendar.getInstance();Row contentRow;float defaultRowHeight = analysisSheet.getDefaultRowHeightInPoints();DateFormat formatter = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm a");int sNo = 0;int addrCol = 11, itemOffset = addrCol + 1, orderOffset = itemOffset + 4;for (User u : users) {rowNo++;sNo++;contentRow = analysisSheet.createRow(rowNo);contentRow.createCell(0).setCellValue(sNo);contentRow.createCell(1).setCellValue(u.getUserId());contentRow.createCell(2).setCellValue(u.getEmail());contentRow.createCell(3).setCellValue(u.getName());contentRow.createCell(4).setCellValue(u.getCommunicationEmail());contentRow.createCell(5).setCellValue(u.getDateOfBirth());// calendar.setTimeInMilliscontentRow.createCell(6).setCellValue(u.getSex().name());contentRow.createCell(7).setCellValue(u.getMobileNumber());calendar.setTimeInMillis(u.getActiveSince());contentRow.createCell(8).setCellValue(formatter.format(calendar.getTime()));calendar.setTimeInMillis(u.getLastLogin());contentRow.createCell(9).setCellValue(formatter.format(calendar.getTime()));Cart cart = null;try {System.out.println("User Id : " + u.getUserId());cart = uClient.getCurrentCart(u.getUserId());} catch (TException e) {logger.error("Error while getting the cart of the user:" + u.getUserId(), e);} catch (ShoppingCartException e) {logger.error("Unable to get the cart for the user:" + u.getUserId());}contentRow.createCell(10).setCellValue((cart != null) ? cart.getId() + "" : "");for(int i = 0; i <= addrCol - 1; i++) {contentRow.getCell(i).setCellStyle(styleUser);}List<Address> addresses = u.getAddresses();int len, addrColWidth = 40;analysisSheet.setColumnWidth(addrCol, addrColWidth * 256); /* set width of address column to 40 characters */String addressString = getAddress(addresses, u.getDefaultAddressId(), (cart != null ? cart.getAddressId() : 0));contentRow.createCell(addrCol).setCellValue(addressString);contentRow.getCell(addrCol).setCellStyle(styleWT);len = addressString.length();if (len > 40) {contentRow.setHeightInPoints((len / addrColWidth + 1) * defaultRowHeight); /* Setting Row Height */}if (cart != null) {List<Line> lines = cart.getLines();if (lines != null && !lines.isEmpty()) {Item catalogItem;for (Line line : lines) {try {catalogItem = cClient.getItem(line.getItemId());if (catalogItem == null) {continue;}rowNo++;contentRow = analysisSheet.createRow(rowNo);contentRow.createCell(itemOffset + 0).setCellValue(catalogItem.getId());contentRow.createCell(itemOffset + 1).setCellValue(catalogItem.getBrand());contentRow.createCell(itemOffset + 2).setCellValue(catalogItem.getModelName());contentRow.createCell(itemOffset + 3).setCellValue(catalogItem.getModelNumber());// linesCount++;// rowNo++;} catch (CatalogServiceException e) {logger.error("Unable to get the item:" + line.getItemId(), e);} catch (TException e) {logger.error("Error while getting the item:" + line.getItemId(), e);}for(int i = itemOffset; i < orderOffset; i++) {contentRow.getCell(i).setCellStyle(styleItem);}}}List<Transaction> transactions;try {transactions = tClient.getTransactionsForShoppingCartId(cart.getId());if (transactions != null && !transactions.isEmpty()) {List<Order> orders;// int ordersRowNo = rowNo - linesCount;for (Transaction txn : transactions) {orders = txn.getOrders();if (orders == null || orders.isEmpty()) {continue;}LineItem lineItem;for (Order o : orders) {lineItem = o.getLineitems().get(0);rowNo++;contentRow = analysisSheet.createRow(rowNo);contentRow.createCell(orderOffset + 0).setCellValue(o.getId());contentRow.createCell(orderOffset + 1).setCellValue(o.getStatus().name());contentRow.createCell(orderOffset + 2).setCellValue(o.getStatusDescription());contentRow.createCell(orderOffset + 3).setCellValue(o.getTotal_amount());contentRow.createCell(orderOffset + 4).setCellValue(lineItem.getBrand());contentRow.createCell(orderOffset + 5).setCellValue(lineItem.getModel_name());contentRow.createCell(orderOffset + 6).setCellValue(lineItem.getModel_number());for(int i = orderOffset; i < orderOffset + 6; i++) {contentRow.getCell(i).setCellStyle(styleOrder);}}}}} catch (TransactionServiceException e) {logger.error("Unable to get the details of the orders", e);} catch (TException e) {logger.error("Error while getting the details of the orders", e);}}}for (int i = 0; i <= 22; i++) {if (i == addrCol) {continue;}analysisSheet.autoSizeColumn(i);}// Write the workbook to the output streamtry {wb.write(baosXLS);baosXLS.close();} catch (IOException e) {logger.error("Erro while writing to the byte array", e);}return baosXLS;}private String getAddress(List<Address> addresses, long defaultAddrId, long cartAddrId) {String addressString = null;if (addresses == null || addresses.isEmpty()) {return "";}for (Address a : addresses) {if (a.getId() == cartAddrId) {addressString = generateAddressString(a);break;}}if (addressString == null) {for (Address a : addresses) {if (a.getId() == defaultAddrId) {addressString = generateAddressString(a);break;}}}return addressString == null ? "" : addressString;}private String generateAddressString(Address a) {String addrStr = "";addrStr += "Name: " + getStringValue(a.getName());addrStr += "; Address: " + getStringValue(a.getLine1());addrStr += ", " + getStringValue(a.getLine2());addrStr += "; City: " + getStringValue(a.getCity());addrStr += "; State: " + getStringValue(a.getState());addrStr += "; Pin: " + getStringValue(a.getPin());addrStr += "; Phone: " + getStringValue(a.getPhone());return addrStr;}private String getStringValue(String str) {return str == null ? "" : str.trim();}public static void main(String[] args) throws ShoppingCartException {DateFormat df = new SimpleDateFormat("MM/dd/yyyy");Date startDate = null, endDate = null;try {startDate = df.parse("05/07/2011");endDate = df.parse("05/09/2011");} catch (ParseException pe) {logger.error("Error while parsing date", pe);}AnalysisDataGenerator adg = new AnalysisDataGenerator();try {String userHome = System.getProperty("user.home");FileOutputStream f = new FileOutputStream(userHome + "/analysis-data.xls");ByteArrayOutputStream baosXLS = adg.generateAnalysisReport(startDate.getTime(), endDate.getTime());if (baosXLS == null) {System.out.println("No data");return;}baosXLS.writeTo(f);f.close();} catch (FileNotFoundException e) {logger.error("Unable to create file", e);} catch (IOException e) {logger.error("Error while creating the analysis report", e);}System.out.println("Successfully generated the analysis report");}}