Rev 26638 | Rev 26821 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.common.util;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.Serializable;import java.net.URISyntaxException;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;import javax.mail.Multipart;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import org.apache.commons.io.FileUtils;import org.apache.commons.io.IOUtils;import org.apache.commons.lang3.StringEscapeUtils;import org.apache.commons.lang3.StringUtils;import org.apache.http.client.utils.URIBuilder;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;import org.springframework.core.io.InputStreamSource;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import com.google.gson.Gson;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.GstRate;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.web.client.RestClient;import com.spice.profitmandi.thrift.clients.CatalogClient;import com.spice.profitmandi.thrift.clients.InventoryClient;import com.spice.profitmandi.thrift.clients.TransactionClient;import com.spice.profitmandi.thrift.clients.UserClient;import com.spice.profitmandi.thrift.clients.WarehouseClient;import com.spice.profitmandi.thrift.clients.config.ConfigClient;import in.shop2020.model.v1.catalog.CatalogService;import in.shop2020.model.v1.inventory.InventoryService;import in.shop2020.model.v1.inventory.StateInfo;import in.shop2020.model.v1.inventory.Warehouse;import in.shop2020.model.v1.order.OrderStatusGroups;import in.shop2020.model.v1.order.RechargeOrderStatus;import in.shop2020.model.v1.order.RechargePlan;import in.shop2020.model.v1.order.RechargeType;import in.shop2020.model.v1.order.SellerInfo;import in.shop2020.model.v1.order.WarehouseAddress;import in.shop2020.model.v1.user.Sex;import in.shop2020.model.v1.user.User;import in.shop2020.model.v1.user.UserContextException;import in.shop2020.warehouse.InventoryItem;import in.shop2020.warehouse.WarehouseService;public class Utils {private static final Logger logger = LogManager.getLogger(Utils.class);public static final String EXPORT_ENTITIES_PATH = getExportPath();public static final String PRODUCT_PROPERTIES_SNIPPET = "ProductPropertiesSnippet.html";public static final String DOCUMENT_STORE = "/profitmandi/documents/";private Gson gson = new Gson();private static final Map<Integer, String> helpMap = new HashMap<>(6);private static final Map<Integer, String> dthIdAliasMap = new HashMap<>(7);private static Map<Long, List<RechargePlan>> operatorPlanMap = new HashMap<>(20);private static Map<Long, String> mobileProvidersMap;private static Map<Long, String> dthProvidersMap;private static final String SMS_GATEWAY = "https://bmg.spicedigital.in/SMSGateway/messagePush";private static Map<Long, String> allProviders;public static Map<RechargeOrderStatus, String> rechargeStatusMap = new HashMap<>();public static OrderStatusGroups ORDER_STATUS_GROUPS = new OrderStatusGroups();public static final String SYSTEM_PARTNER = "testpxps@gmail.com";private static final RestClient rc = new RestClient();static {helpMap.put(Integer.valueOf(1), "Your VC number starts with 0 and is 11 digits long.");helpMap.put(Integer.valueOf(2), "Smart card number starts with 2 and is 12 digits long.");helpMap.put(Integer.valueOf(3), "Smart card number starts with 4 and is 11 digits long.");helpMap.put(Integer.valueOf(4), "Subscriber ID starts with 1 and is 10 digits long.");helpMap.put(Integer.valueOf(5), "For customer ID, SMS ID to 9212012299 from your registered mobile no.");helpMap.put(Integer.valueOf(26), "Customer ID starts with 3 and is 10 digits long.");dthIdAliasMap.put(Integer.valueOf(1), "VC Number :");dthIdAliasMap.put(Integer.valueOf(2), "Smart Card Number :");dthIdAliasMap.put(Integer.valueOf(3), "Smart Card Number :");dthIdAliasMap.put(Integer.valueOf(4), "Subscriber Id :");dthIdAliasMap.put(Integer.valueOf(5), "Customer Id :");dthIdAliasMap.put(Integer.valueOf(0), "Account Number :");dthIdAliasMap.put(Integer.valueOf(26), "Customer Id :");rechargeStatusMap.put(RechargeOrderStatus.PAYMENT_FAILED, "Payment Unsuccessful");rechargeStatusMap.put(RechargeOrderStatus.PAYMENT_SUCCESSFUL, "Processing Recharge");rechargeStatusMap.put(RechargeOrderStatus.RECHARGE_FAILED, "Recharge Failed");rechargeStatusMap.put(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, "Recharge Failed Refunded");rechargeStatusMap.put(RechargeOrderStatus.RECHARGE_SUCCESSFUL, "Recharge Successful");rechargeStatusMap.put(RechargeOrderStatus.REFUNDED, "Amount Refunded");rechargeStatusMap.put(RechargeOrderStatus.PARTIALLY_REFUNDED, "Amount Refunded");rechargeStatusMap.put(RechargeOrderStatus.PAYMENT_PENDING, "Payment Failed");rechargeStatusMap.put(RechargeOrderStatus.INIT, "Payment Initiated");rechargeStatusMap.put(RechargeOrderStatus.RECHARGE_UNKNOWN, "Recharge In Process");rechargeStatusMap.put(RechargeOrderStatus.RECHARGE_IN_PROCESS, "Recharge In Process");TransactionClient tcl;try {tcl = new TransactionClient();mobileProvidersMap = tcl.getClient().getServiceProviders(RechargeType.MOBILE, true);dthProvidersMap = tcl.getClient().getServiceProviders(RechargeType.DTH, true);logger.info("mobileProvidersMap" + mobileProvidersMap);logger.info("dthProvidersMap" + dthProvidersMap);allProviders = new HashMap<>(mobileProvidersMap);logger.info("allProviders" + allProviders);allProviders.putAll(dthProvidersMap);logger.info("allProviders" + allProviders);for (Long operatorId : mobileProvidersMap.keySet()) {List<RechargePlan> plans = tcl.getClient().getPlansForOperator(operatorId.longValue());if (!plans.isEmpty())operatorPlanMap.put(operatorId, plans);}} catch (Exception e) {logger.error("Could not get providers", e);}}public static SellerInfo getSellerInfoBySellerId(int sellerId) throws Exception {TransactionClient tcl = new TransactionClient();return tcl.getClient().getSellerInfo((long) sellerId);}@SuppressWarnings("serial")public static final Map<String, String> MIME_TYPE = Collections.unmodifiableMap(new HashMap<String, String>() {{put("image/png", "png");put("image/jpeg", "jpeg");put("image/pjpeg", "jpeg");put("application/pdf", "pdf");}});private static String getExportPath() {String exportPath = "/var/lib/tomcat7/webapps/export/html/entities/";/* String exportPath = null;try {ConfigClient client = ConfigClient.getClient();exportPath = client.get("export_entities_path");} catch (Exception ce) {logger.error("Unable to read export path from the config client: ", ce);logger.warn("Setting the default export path");exportPath = "/var/lib/tomcat7/webapps/export/html/entities/";}*/return exportPath;}public static String getRechargeDisplayStatus(RechargeOrderStatus status) {if (status == null) {status = RechargeOrderStatus.INIT;}String displayStatus = (String) rechargeStatusMap.get(status);if (displayStatus == null) {return "";}return displayStatus;}public static boolean copyDocument(String documentPath) {File source = new File(documentPath);File dest = new File(DOCUMENT_STORE + source.getName());try {FileUtils.copyFile(source, dest);} catch (IOException e) {e.printStackTrace();return false;}return true;}public static Map<Long, String> getMobileProvidersMap() {return mobileProvidersMap;}public static Map<Long, String> getDthProvidersMap() {return dthProvidersMap;}public static Map<Long, String> getAllProviders() {return allProviders;}public static String getProvider(long operatorId) {return allProviders.get(operatorId);}public static void sendSms(String text, String mobileNumber) throws Exception {Map<String, String> paramsMap = new HashMap<>();paramsMap.put("username", "SmartDukaanT");paramsMap.put("password", "Smart@91");paramsMap.put("senderID", "SMTDKN");paramsMap.put("message", text);paramsMap.put("mobile", mobileNumber);paramsMap.put("messageType", "Text");rc.getResponse(SMS_GATEWAY, paramsMap, null);}public static void sendMailWithAttachments(JavaMailSender mailSender, String emailTo, String[] cc, String subject,String body, List<File> attachments) throws Exception {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setSubject(subject);helper.setText(body);if (cc != null) {helper.setCc(cc);}helper.setTo(emailTo);InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");helper.setFrom(senderAddress);if (attachments != null) {for (File file : attachments) {helper.addAttachment(file.getName(), file);}}mailSender.send(message);}public static class Attachment {public Attachment(String fileName, InputStreamSource inputStreamSource) {this.fileName = fileName;this.inputStreamSource = inputStreamSource;}private String fileName;private InputStreamSource inputStreamSource;public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public InputStreamSource getInputStreamSource() {return inputStreamSource;}public void setInputStreamSource(InputStreamSource inputStreamSource) {this.inputStreamSource = inputStreamSource;}@Overridepublic String toString() {return "Attachment [fileName=" + fileName + ", inputStreamSource=" + inputStreamSource + "]";}}public static void sendMailWithAttachment(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,String body, String fileName, InputStreamSource inputStreamSource) throws Exception {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setSubject(subject);helper.setText(body);if (cc != null) {helper.setCc(cc);}helper.setTo(emailTo);helper.addAttachment(fileName, inputStreamSource);InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");helper.setFrom(senderAddress);mailSender.send(message);}public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,String body, Attachment... attachments) throws Exception {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setSubject(subject);helper.setText(body);if (cc != null) {helper.setCc(cc);}helper.setTo(emailTo);for (Attachment attachment : attachments) {helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());}InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");helper.setFrom(senderAddress);mailSender.send(message);}public static void sendHtmlMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc,String subject, String body, Attachment... attachments) throws Exception {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setSubject(subject);message.setContent(body, "text/html");// helper.setText(body, true);if (cc != null) {helper.setCc(cc);}helper.setTo(emailTo);for (Attachment attachment : attachments) {if (attachment == null)break;helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());}InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");helper.setFrom(senderAddress);mailSender.send(message);}public static String[] getOrderStatus(RechargeOrderStatus status) {if (status == null) {status = RechargeOrderStatus.INIT;}if (status.equals(RechargeOrderStatus.PAYMENT_FAILED) || status.equals(RechargeOrderStatus.PAYMENT_PENDING)) {return new String[] { "false", "PAYMENT FAILED", "Payment failed at the payment gateway." };} else if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)|| status.equals(RechargeOrderStatus.RECHARGE_UNKNOWN)) {if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)) {return new String[] { "false", "PAYMENT SUCCESSFUL","Your Payment was successful but due to some internal error with the operator's system we are not sure if the recharge was successful."+ " We have put your recharge under process."+ " As soon as we get a confirmation on this transaction, we will notify you." };} else {return new String[] { "false", "RECHARGE IN PROCESS","Your Payment is successful.We have put your recharge under process."+ " Please wait while we check with the operator." };}} else if (status.equals(RechargeOrderStatus.RECHARGE_FAILED)|| status.equals(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)) {return new String[] { "false", "RECHARGE FAILED","Your Payment was successful but unfortunately the recharge failed.Don't worry your payment is safe with us."+ " The entire Amount has been refunded to your wallet." };} else if (status.equals(RechargeOrderStatus.RECHARGE_SUCCESSFUL)) {return new String[] { "false", "SUCCESS", "Congratulations! Your device is successfully recharged." };} else if (status.equals(RechargeOrderStatus.PARTIALLY_REFUNDED)|| status.equals(RechargeOrderStatus.REFUNDED)) {return new String[] { "false", "PAYMENT REFUNDED","The payment associated with this recharge order has been refunded." };} else {return new String[] { "true", "ERROR", "INVALID INPUT" };}}public static String getIconUrl(int entityId, String host, int port, String webapp) {return "";}public static Map<Integer, GstRate> getStateTaxRate(List<Integer> itemIds, int stateId)throws ProfitMandiBusinessException {List<Long> longItemIds = new ArrayList<>();for (int itemId : itemIds) {longItemIds.add(Long.valueOf(itemId));}try {CatalogService.Client catalogClient = getCatalogClient();Map<Long, in.shop2020.model.v1.catalog.GstRate> totalTaxRateMap = catalogClient.getStateTaxRate(longItemIds,stateId);Map<Integer, GstRate> itemIdGstRateMap = new HashMap<>();for (Map.Entry<Long, in.shop2020.model.v1.catalog.GstRate> totalTaxRateEntry : totalTaxRateMap.entrySet()) {GstRate gstRate = new GstRate();gstRate.setIgstRate(Double.valueOf(totalTaxRateEntry.getValue().getIgstRate()).floatValue());gstRate.setCgstRate(Double.valueOf(totalTaxRateEntry.getValue().getCgstRate()).floatValue());gstRate.setSgstRate(Double.valueOf(totalTaxRateEntry.getValue().getSgstRate()).floatValue());itemIdGstRateMap.put(totalTaxRateEntry.getKey().intValue(), gstRate);}return itemIdGstRateMap;} catch (Exception e) {e.printStackTrace();throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID + ", " + ProfitMandiConstants.STATE_ID,itemIds + ", " + stateId, "THRFT_1000");}}public static Map<Integer, Float> getIgstTaxRate(List<Integer> itemIds) throws ProfitMandiBusinessException {List<Long> longItemIds = new ArrayList<>();for (int itemId : itemIds) {longItemIds.add(Long.valueOf(itemId));}try {CatalogService.Client catalogClient = getCatalogClient();Map<Long, Double> totalTaxRateMap = catalogClient.getIgstTaxRate(longItemIds);Map<Integer, Float> itemIdIgstRateMap = new HashMap<>();for (Map.Entry<Long, Double> totalTaxRateEntry : totalTaxRateMap.entrySet()) {itemIdIgstRateMap.put(totalTaxRateEntry.getKey().intValue(), 12f);}return itemIdIgstRateMap;} catch (Exception e) {e.printStackTrace();throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, itemIds, "THRFT_1001");}}private static CatalogService.Client getCatalogClient() throws Exception {try {CatalogClient client = new CatalogClient();CatalogService.Client catalogClient = client.getClient();return catalogClient;} catch (Exception e) {throw e;}}private static WarehouseService.Client getWarehouseClient() throws Exception {try {WarehouseClient client = new WarehouseClient();WarehouseService.Client warehouseClient = client.getClient();return warehouseClient;} catch (Exception e) {throw e;}}public static Map<String, Warehouse> getWarehouseByImeis(List<String> imeis) throws Exception {List<InventoryItem> inventoryItems = getWarehouseClient().getInventoryItemsBySerailNumbers(imeis);Map<String, InventoryItem> imeiInventoryItemMap = new HashMap<>();for (InventoryItem inventoryItem : inventoryItems) {imeiInventoryItemMap.put(inventoryItem.getSerialNumber(), inventoryItem);}Map<Integer, Warehouse> warehouseMap = new HashMap<>();Map<String, Warehouse> serialNumberWarehouseMap = new HashMap<>();InventoryClient client = new InventoryClient();InventoryService.Client inventoryClient = client.getClient();logger.info("[imeiInventoryItemMap] {}", imeiInventoryItemMap);for (InventoryItem inventory : new HashSet<>(imeiInventoryItemMap.values())) {Warehouse phWarehouse = null;if (warehouseMap.containsKey(inventory.getPhysicalWarehouseId())) {phWarehouse = warehouseMap.get((int) inventory.getPhysicalWarehouseId());} else {phWarehouse = inventoryClient.getWarehouse(inventory.getPhysicalWarehouseId());warehouseMap.put((int) inventory.getPhysicalWarehouseId(), phWarehouse);}serialNumberWarehouseMap.put(inventory.getSerialNumber(), phWarehouse);}return serialNumberWarehouseMap;}public static Map<Integer, Warehouse> getWarehousesByIds(Set<Integer> warehouseIds) throws Exception {InventoryClient client = new InventoryClient();InventoryService.Client inventoryClient = client.getClient();Map<Integer, Warehouse> warehouseMap = new HashMap<>();for (Integer warehouseId : warehouseIds) {warehouseMap.put(warehouseId, inventoryClient.getWarehouse(warehouseId));}return warehouseMap;}public static String getStateCode(String stateName) throws Exception {return getStateInfo(stateName).getStateCode();}public static long getStateId(String stateName) throws ProfitMandiBusinessException {try {return getStateInfo(stateName).getId();} catch (Exception e) {e.printStackTrace();throw new ProfitMandiBusinessException("State Name", stateName, "Could not fetch state");}}public static StateInfo getStateByStateId(long stateId) throws Exception {InventoryClient client = new InventoryClient();InventoryService.Client inventoryClient = client.getClient();Map<Long, StateInfo> map = inventoryClient.getStateMaster();return map.get(stateId);}public static StateInfo getStateInfo(String stateName) throws Exception {try {InventoryClient client = new InventoryClient();InventoryService.Client inventoryClient = client.getClient();Map<Long, StateInfo> map = inventoryClient.getStateMaster();List<StateInfo> stateInfos = new ArrayList<>(map.values());logger.info("State Name: {}", stateName);for (StateInfo stateInfo : stateInfos) {logger.info("State Name from service: {}", stateInfo.getStateName());if (stateName.toUpperCase().equals(stateInfo.getStateName().toUpperCase())) {return stateInfo;}}throw new Exception("Not found");} catch (Exception e) {e.printStackTrace();throw e;}}public static List<String> getAllStateNames() {List<String> sortedStateNames = new ArrayList<>();try {InventoryClient client = new InventoryClient();InventoryService.Client inventoryClient = client.getClient();Map<Long, StateInfo> map = inventoryClient.getStateMaster();List<StateInfo> stateInfos = new ArrayList<>(map.values());Set<String> stateNames = new TreeSet<>();for (StateInfo stateInfo : stateInfos) {stateNames.add(stateInfo.getStateName());}sortedStateNames = new ArrayList<>(stateNames);return sortedStateNames;} catch (Exception e) {e.printStackTrace();return sortedStateNames;}}public static Map<Long, StateInfo> getAllStatesMap() throws Exception {InventoryClient client = new InventoryClient();InventoryService.Client inventoryClient = client.getClient();return inventoryClient.getStateMaster();}public static User createSaholicUser(String emailId) throws ProfitMandiBusinessException {in.shop2020.model.v1.user.User user = new in.shop2020.model.v1.user.User();user.setEmail(emailId);user.setPassword("");user.setCommunicationEmail(emailId);user.setSex(Sex.WONT_SAY);try {UserClient userContextServiceClient = new UserClient();in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();user = userClient.createUser(user);return user;} catch (UserContextException ux) {logger.error("Unable to register user: " + ux.getMessage());throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, emailId, "");} catch (TTransportException e) {logger.error("Unable to register user." + e);throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, emailId, "");} catch (TException e) {logger.error("Unable to register user." + e);throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, emailId, "");}}public static void main(String[] args) throws Exception {Utils.sendSms("Hello", "9990381569");}public static WarehouseAddress getWarehouseByWarehouseId(int warehouseAddressId) throws Exception {TransactionClient tcl = new TransactionClient();return tcl.getClient().getWarehouseAddress((long) warehouseAddressId);}public static void sendEmbeddedHtmlMail(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,String body, Map<? extends Serializable, File> map) throws Exception {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setSubject(subject);Multipart mp = new MimeMultipart();MimeBodyPart messageBodyPart = new MimeBodyPart();messageBodyPart.setContent(body, "text/html");mp.addBodyPart(messageBodyPart);// helper.setText(body, true);if (cc != null) {helper.setCc(cc);}helper.setTo(emailTo);InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");helper.setFrom(senderAddress);for (Map.Entry<? extends Serializable, File> entry : map.entrySet()) {entry.getKey();entry.getValue();MimeBodyPart imagePart = new MimeBodyPart();imagePart.setHeader("Content-ID", entry.getKey() + "");imagePart.setDisposition(MimeBodyPart.INLINE);imagePart.attachFile(entry.getValue());mp.addBodyPart(imagePart);}message.setContent(mp);mailSender.send(message);}public String htmlJson(Object object) {return StringEscapeUtils.escapeHtml4(gson.toJson(object));}public static String getHyphenatedString(String s) {s = s.trim().replaceAll("\\s+", " ");s = s.replaceAll("\\s", "-");return s.toLowerCase();}}