rendered paste bodypackage com.tcm.nestle.controllers;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.tcm.framework.common.SysConstants;import com.tcm.framework.utils.CommunicationUtil;import com.tcm.framework.utils.DateUtils;import com.tcm.framework.utils.FileUtils;import com.tcm.framework.utils.StringUtils;import com.tcm.framework.webcontroller.BaseController;import com.tcm.nestle.bo.AssetTracking;import com.tcm.nestle.bo.PopImages;import com.tcm.nestle.bo.Remarks;import com.tcm.nestle.bo.ShopAsset;import com.tcm.nestle.bo.Survey;import com.tcm.nestle.bo.SurveyDetail;import com.tcm.nestle.bo.SurveyImages;import com.tcm.nestle.dao.MerchandiserDao;import com.tcm.nestle.dao.SurveyorDao;public class UploadShopDataServlet extends BaseController { /** * */ private static final long serialVersionUID = 1L; private static Logger logger = Logger .getLogger(UploadShopDataServlet.class); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CommunicationUtil utils = new CommunicationUtil(); StringBuffer buffer = new StringBuffer(); MerchandiserDao merchandizerDao = new MerchandiserDao(); String updateCount = request.getHeader(SysConstants.UPDATE_COUNT); InputStream in = request.getInputStream(); // reading data int survayorId = utils.readInt(in); buffer.append("survayorId="+survayorId); int rootId = utils.readInt(in); buffer.append(", rootId="+rootId); int shopId = utils.readInt(in); buffer.append(", shopId="+shopId); int channelId = utils.readInt(in); buffer.append(", channelId="+channelId); int remarkId = utils.readInt(in); buffer.append(", remarkId="+remarkId); String surveyDatetime = utils.readString(in); buffer.append(", surveyDatetime="+surveyDatetime); SurveyorDao surveyorDao = new SurveyorDao(); int lastUpdateCountt = surveyorDao.getUpdateCount(survayorId); if (Integer.parseInt(updateCount) < lastUpdateCountt) { response.setHeader(SysConstants.UPDATE_COUNT, lastUpdateCountt + ""); } else { response.setHeader(SysConstants.UPDATE_COUNT, updateCount); } // setting data into bean logger.info("##############################################################");// logger.info("ServeyorId = " + survayorId);// logger.info("rootId = " + rootId);// logger.info("shopId = " + shopId);// logger.info("shpVisited timeStamp = " + surveyDatetime); Survey survey = new Survey(); int imageAvaliable = utils.readInt(in); buffer.append(", shopimageAvalb="+imageAvaliable); if (imageAvaliable == 1) { survey.setShopImage(utils.readImage(in)); buffer.append(", ShopImage="+survey.getShopImage()); survey.setShopImageDatetime(utils.readString(in)); buffer.append(", ShopImageDatetime="+survey.getShopImageDatetime()); // logger.info("getShopImageDatetime = " + survey.getShopImageDatetime() + " " + survey.getShopImage()); } int actionSize = utils.readInt(in); buffer.append(", actionSize="+actionSize); ShopAsset asset = null; SurveyImages surImage = new SurveyImages(); for (int i = 0; i < actionSize; i++) { surImage = new SurveyImages(); int assetTypeId = utils.readInt(in); buffer.append(", assetTypeId="+assetTypeId); String chillerCode = utils.readString(in); buffer.append(", chillerCode="+chillerCode); // surImage.setAssetCode(); surImage.setRemarksId(utils.readInt(in)); buffer.append(", RemarksId="+surImage.getRemarksId()); surImage.setAssetTypeCategryId(assetTypeId); if(assetTypeId == 2){ if(!StringUtils.isNullOrEmptyString(chillerCode)){ asset= new ShopAsset(); asset.setShopId(shopId); asset.setAssetTypeName(chillerCode); } } imageAvaliable = utils.readInt(in); buffer.append(", imageAvaliable=" + imageAvaliable); // logger.info("beforeImageAvailable = " + imageAvaliable); if (imageAvaliable == 1) { byte[] beforeImag = utils.readImage(in); String beforeimageTime = utils.readString(in); buffer.append(", beforeImag=" + beforeImag); buffer.append(", beforeimageTime=" + beforeimageTime); surImage.setBeforeImage(beforeImag);; surImage.setImageBeforeTime(beforeimageTime); // logger.info("tiemBefore = " + beforeimageTime + " " + beforeImag ); } imageAvaliable = utils.readInt(in); buffer.append(", afterimageAvailable=" + imageAvaliable); // logger.info("afterImageAvailable = " + imageAvaliable); if (imageAvaliable == 1) { byte[] afterImag = utils.readImage(in); String afterimageTime = utils.readString(in); buffer.append(", afterImag=" + afterImag); buffer.append(", afterimageTime=" + afterimageTime); surImage.setAfterImage(afterImag); surImage.setImage_after_time(afterimageTime);// logger.info("tiemAfter = " + afterimageTime+ " " + afterImag ); } survey.addImage(surImage); } ArrayList<String> timesList = new ArrayList<String>(); int timeSize = utils.readInt(in); for(int i=0; i<timeSize; i++){ timesList.add(utils.readString(in)); } survey.setSurveyorId(survayorId); survey.setSurveyShopId(shopId); survey.setChannelId(channelId); survey.setRemarkId(remarkId); survey.setVisittime(surveyDatetime);// logger.info(" getSurvey_visittime = "+ survey.getVisittime()); survey.setRouteId(rootId); SurveyDetail surveyDetail = null; ArrayList<SurveyDetail> surveyDetailList = new ArrayList<SurveyDetail>(); StringBuilder temp = new StringBuilder(); int productCount = utils.readInt(in); for (int i = 0; i < productCount; i++) { surveyDetail = new SurveyDetail(); int productId = utils.readInt(in); String availableValue = utils.readString(in);// int facingValue = utils.readInt(in); temp.append("(").append(productId).append("-").append(availableValue).append("), "); surveyDetail.setProduct_id(productId); surveyDetail.setUnit_available(availableValue);// surveyDetail.setFace_unit(facingValue);// logger.info(surveyDetail); surveyDetailList.add(surveyDetail); } int isPopIssued = utils.readInt(in); buffer.append(", isPopIssued=" + isPopIssued); if(isPopIssued >0){ int popIssuedRouteId = utils.readInt(in); int postersIssuesSize = utils.readInt(in); int buntingIssuesSize = utils.readInt(in); int selfTikkerIssizeSize = utils.readInt(in); int bannerIssuesSize = utils.readInt(in); buffer.append(", postersIssuesSize=" + postersIssuesSize) .append(", buntingIssuesSize=" + buntingIssuesSize) .append(", selfTikkerIssizeSize=" + selfTikkerIssizeSize) .append(", bannerIssuesSize=" + bannerIssuesSize); merchandizerDao.updatePopIssuedData(survayorId, popIssuedRouteId, postersIssuesSize, buntingIssuesSize, selfTikkerIssizeSize, bannerIssuesSize); } PopImages images = new PopImages(); int PopImageAvaliable = utils.readInt(in); buffer.append(", imageAvaliable=" + imageAvaliable); if (PopImageAvaliable == 1) { byte[] popImage = utils.readImage(in); String popImageTime = utils.readString(in); buffer.append(", popImage=" + popImage); buffer.append(", popImageTime=" + popImageTime); images.setFirstPopImage(popImage);; images.setFirstPopImageTime(popImageTime); } int PopImageAvaliable2 = utils.readInt(in); buffer.append(", PopImageAvaliable2=" + PopImageAvaliable2); if (PopImageAvaliable2 == 1) { byte[] popImage2 = utils.readImage(in); String popImageTime2 = utils.readString(in); buffer.append(", popImage2=" + popImage2); buffer.append(", popImageTime2=" + popImageTime2); images.setSecondPopImage(popImage2); images.setSecondPopImageTime(popImageTime2); } int isddDataAvalible = utils.readInt(in); if(isddDataAvalible == 1){ String ddAvalible = utils.readString(in); int ddImageAvaliable = utils.readInt(in); buffer.append(", ddImageAvaliable =" + ddImageAvaliable); if (ddImageAvaliable == 1) { byte[] ddImage = utils.readImage(in); String ddImageTime = utils.readString(in); buffer.append(", ddImage=" + ddImage); buffer.append(", ddImageTime=" + ddImageTime); images.setFirstDDImage(ddImage);; images.setFirstDDImageTime(ddImageTime); } int ddImageAvaliable2 = utils.readInt(in); buffer.append(", ddImageAvaliable2=" + ddImageAvaliable2); if (ddImageAvaliable2 == 1) { byte[] ddImage2 = utils.readImage(in); String ddImageTime2 = utils.readString(in); buffer.append(", ddImage2=" + ddImage2); buffer.append(", ddImageTime2=" + ddImageTime2); images.setSecondDDImage(ddImage2); images.setSecondDDImageTime(ddImageTime2); } images.setIsDDAvalible(ddAvalible); } survey.setPopImage(images); int retailerRemarkSize = utils.readInt(in); for (int i = 0; i < retailerRemarkSize; i++) { int remarksId = utils.readInt(in); String retailerRemark = utils.readString(in); Remarks remark = new Remarks(); remark.setId(remarksId); remark.setRemark(retailerRemark); survey.addretailerRemarks(remark); } int assetTrackingSize = utils.readInt(in); for (int i = 0; i < assetTrackingSize; i++) { int assetId = utils.readInt(in); String isAvalible = utils.readString(in); AssetTracking assetTracking = new AssetTracking(); assetTracking.setAssetId(assetId); assetTracking.setIsAvalible(isAvalible); survey.addAssetTracking(assetTracking); } buffer.append(", productCount=" + productCount); logger.info("SurveyayData = " + buffer.toString()); buffer.append(temp.toString()); logger.info("##############################################################"); survey.setSurveyDetail(surveyDetailList); int id = merchandizerDao.isMerchandiseSurveyAlreadyExist(survey.getSurveyorId(), shopId, survey.getRouteId(), survey.getVisittime()); int result = 0; int logResult = 0; if (id != -1) { merchandizerDao.deleteSurveyProduect(id); merchandizerDao.deleteSurveyImages(id); merchandizerDao.deleteSurvey(id); result = merchandizerDao.insertDublicateSurveyDetail(survey); if (productCount > 0 && productCount < 1000) { result = merchandizerDao.insertSurveyDetail(survey); } else { int logCount = merchandizerDao.isLogSurveyAlreadyExist(shopId); if (logCount > 0) { int count = merchandizerDao.getLogDublicateCount(logCount); if (count >= 3) { logResult = 1; } else { merchandizerDao.updateLogSurveyData(logCount); logResult = 0; } } else { merchandizerDao.insertLogSurveyDetail(survey); logResult = 0; } } } else { if (productCount > 0 && productCount < 1000) { result = merchandizerDao.insertSurveyDetail(survey); } else { int logCount = merchandizerDao.isLogSurveyAlreadyExist(shopId); if (logCount > 0) { int count = merchandizerDao.getLogDublicateCount(logCount); if (count >= 3) { logResult = 1; } else { merchandizerDao.updateLogSurveyData(logCount); logResult = 0; } } else { merchandizerDao.insertLogSurveyDetail(survey); logResult = 0; } } } if(asset != null){// System.out.println("getShopId = "+asset.getShopId()+" " + asset.getAssetTypeName()); merchandizerDao.updateShopsChillerCode(asset); } // Date surveyDate = DateUtils.stringToDate(survey.getVisittime().split(" ")[0], DateUtils.DB_DATE_FORMAT);// String date = DateUtils.dateToString(surveyDate, "ddMMMyyyy"); String date = DateUtils.getDateString().split(" ")[0]; if(survey.getId() > 0){ date = survey.getVisittime().split(" ")[0];// String fileUrl = getServersContentUrl(); if(survey.getShopImage() != null){ String shopImagePath = SysConstants.IMAGES_SURVEY_FOLDER + date + "/"+ result + "/shop.jpg"; survey.setShopImageUrl(shopImagePath); FileUtils.writeFileBytes(survey.getShopImage(), getServletContext().getRealPath("/")+ shopImagePath); } if (survey.getImageList().size() > 0) { for (SurveyImages image : survey.getImageList()) { String beforeImagePath = SysConstants.IMAGES_SURVEY_FOLDER+ date + "/" + result + "/"+ image.getAssetTypeCategryId() + "/before.jpg"; String afterImagePath = SysConstants.IMAGES_SURVEY_FOLDER+ date + "/" + result + "/"+ image.getAssetTypeCategryId() + "/after.jpg"; image.setSurveyId(result); if (image.getBeforeImage() != null) { image.setBeforeImageUrl(beforeImagePath); FileUtils.writeFileBytes(image.getBeforeImage(),getServletContext().getRealPath("/")+ beforeImagePath); } if (image.getAfterImage() != null) { image.setAfter_image_url(afterImagePath); FileUtils.writeFileBytes(image.getAfterImage(),getServletContext().getRealPath("/")+ afterImagePath); } } } if(survey.getPopImage() != null){ String firstPopImagePath = SysConstants.IMAGES_SURVEY_FOLDER+ date + "/" + result + "/firstPop.jpg"; String secondPopImagePath = SysConstants.IMAGES_SURVEY_FOLDER+ date + "/" + result + "/secondPop.jpg"; String firstddImagePath = SysConstants.IMAGES_SURVEY_FOLDER+ date + "/" + result + "/firstdd.jpg"; String secondddImagePath = SysConstants.IMAGES_SURVEY_FOLDER+ date + "/" + result + "/seconddd.jpg"; if(survey.getPopImage().getFirstPopImage() != null){ survey.getPopImage().setFirstPopImageUrl(firstPopImagePath); FileUtils.writeFileBytes(survey.getPopImage().getFirstPopImage(),getServletContext().getRealPath("/")+ firstPopImagePath); } if(survey.getPopImage().getSecondPopImage() != null){ survey.getPopImage().setSecondPopImageUrl(secondPopImagePath); FileUtils.writeFileBytes(survey.getPopImage().getSecondPopImage(),getServletContext().getRealPath("/")+ secondPopImagePath); } if(survey.getPopImage().getFirstDDImage() != null){ survey.getPopImage().setFirstDDImageUrl(firstddImagePath); FileUtils.writeFileBytes(survey.getPopImage().getFirstDDImage(),getServletContext().getRealPath("/")+ firstddImagePath); } if(survey.getPopImage().getSecondDDImage() != null){ survey.getPopImage().setSecondDDImageUrl(secondddImagePath); FileUtils.writeFileBytes(survey.getPopImage().getSecondDDImage(),getServletContext().getRealPath("/")+ secondddImagePath); } } merchandizerDao.UpdatFilesPath(survey); merchandizerDao.UpdatPopFilesPath(survey); merchandizerDao.UpdatAssetTracking(survey); merchandizerDao.UpdateRetailerRemarks(survey); } if(timesList.size() > 0){ merchandizerDao.updateSurveyorsTime(survayorId, timesList); } response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/octet-stream"); OutputStream os = response.getOutputStream(); if (result > 0 || logResult > 0) { CommunicationUtil.writeInt(os, 1); } else { CommunicationUtil.writeInt(os, 0); } String clientVersion = request.getHeader(SysConstants.UPDATE_VERSION); if(!StringUtils.isNullOrEmptyString(clientVersion)){ merchandizerDao.updateSurveyorAppVersion(survayorId, clientVersion); } logSurveryData(survayorId, survey, date, buffer.toString());// logger.info(survey); } private void logSurveryData(int surveyorID, Survey survey, String date, String data) { String filePath = getServersContentUrl(date)+surveyorID+".txt"; // Writer output = null;// FileWriter fw = null;// // String text = survey.toString();// File file = new File(filePath); String temp = data+"\n"; try { FileUtils.writeFileString(temp, filePath);// if(FileUtils.isExistsFile(filePath)){// fw = new FileWriter(file, true);// }else{// fw = new FileWriter(file);// }// output = new BufferedWriter(fw);// output.write(text);// output.close(); } catch (IOException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } private String getServersContentUrl(String date){ date = DateUtils.getDateString().split(" ")[0];//DateUtils.changeFormat(DateUtils.getCurrentDateString(),"ddMMMyyyy"); String path = getServletContext().getRealPath("/")+"/survey_logs/"+date+"/"; if(!FileUtils.isExistsFolder(path)){ FileUtils.createFolders(path); } return path; }}============ package com.nestlemonitor.main.network;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.Vector;import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.content.DialogInterface.OnCancelListener;import android.os.AsyncTask;import android.util.Log;import com.nestlemonitor.main.bo.AssetTracking;import com.nestlemonitor.main.bo.DataListener;import com.nestlemonitor.main.bo.DisplayDrive;import com.nestlemonitor.main.bo.ImageData;import com.nestlemonitor.main.bo.POPsIssued;import com.nestlemonitor.main.bo.Product;import com.nestlemonitor.main.bo.PruductsValues;import com.nestlemonitor.main.bo.RetailerRemarks;import com.nestlemonitor.main.bo.ShopPOP;import com.nestlemonitor.main.bo.TimeLog;import com.nestlemonitor.main.db.DatabaseHandler;import com.nestlemonitor.main.model.RefreshProducts;import com.nestlemonitor.main.model.RefreshRoots;import com.nestlemonitor.main.model.UploadData;import com.nestlemonitor.main.preferences.UserPreferences;import com.nestlemonitor.main.ui.R;import com.nestlemonitor.main.utils.DataHolder;import com.nestlemonitor.main.utils.Resources;import com.nestlemonitor.main.utils.SuperUploadAbleDataConteiner;import com.nestlemonitor.main.utils.UploadAbleDataConteiner;import com.nestlemonitor.main.utils.Utils;public class HTTPWorkerAsyncTask extends AsyncTask<String, Void, Boolean>{ private int iJobCode = -1; public long currentRequestCode = -1; private DataListener dataListener = null; private Object object = null; private InputStream inputStream = null; private String param[] = null; public boolean isCommunityRequest = false; public String URL = null; private int responseCode=0; private ProgressDialog pdialog; public static final int EXISTING_PERSON = 1; public static final int NEW_PERSON = 2; private HttpURLConnection urlConnection; private ByteArrayOutputStream baOutputStream; private OutputStream outputStream; public static boolean isExceptionOccured = false; private DatabaseHandler dbDatabaseHandler =null; public void setOtherParam(int jobCode, String[] param, String url) {// this.currentRequestCode = requestCode; this.param = param; this.iJobCode = jobCode; this.URL = url; } public void setDataListener(Object object, DataListener dataListener) { Resources.alertTitle = null; Resources.alertMessage = null; this.dataListener = dataListener; this.object = object;// dataListener.setDataReceiver(object); } @Override protected Boolean doInBackground(String... param) { try{ CommunicationUtil utils = new CommunicationUtil(); Log.i("URL", URL); baOutputStream = new ByteArrayOutputStream(); if(iJobCode==NetManger.LOGIN_REQUEST){ utils.writeString(baOutputStream, this.param[0]); }else if(iJobCode==NetManger.REFRESH_ROOT_REQUEST){ utils.writeString(baOutputStream, this.param[0]); }else if(iJobCode==NetManger.REFRESH_PRODUCTS_REQUEST){ utils.writeString(baOutputStream, this.param[0]); }else if(iJobCode==NetManger.UPDATE_PROFILE_REQUEST){ utils.writeString(baOutputStream, this.param[0]); }else if(iJobCode == NetManger.UPLOAD_SHOP_DATA){ utils.writeInt(baOutputStream,Integer.parseInt(this.param[0]));//user id utils.writeInt(baOutputStream, Integer.parseInt(UploadAbleDataConteiner.getDataContainer().getSelectedRootId()));//root id utils.writeInt(baOutputStream, Integer.parseInt(UploadAbleDataConteiner.getDataContainer().getSelectedShopId()));//shop id utils.writeInt(baOutputStream, Integer.parseInt(UploadAbleDataConteiner.getDataContainer().getSelectedChannelId())); //chennel id utils.writeInt(baOutputStream, UploadAbleDataConteiner.getDataContainer().getRemarksId());// remark id utils.writeString(baOutputStream, UploadAbleDataConteiner.getDataContainer().getShopTimeStamp());// time stamp // if(UploadAbleDataConteiner.getDataContainer().getShopImage()!=null && UploadAbleDataConteiner.getDataContainer().getShopImage().length > 0){// utils.writeInt(baOutputStream, 1);// utils.writeImage(baOutputStream, UploadAbleDataConteiner.getDataContainer().getShopImage());// Log.i("SHOP IMAGE TIME", "<><><>"+UploadAbleDataConteiner.getDataContainer().getShopPictureTimeStamp());// utils.writeString(baOutputStream, UploadAbleDataConteiner.getDataContainer().getShopPictureTimeStamp());// }else{// utils.writeInt(baOutputStream, 0);// }// if(UploadAbleDataConteiner.getDataContainer().getBeforImage()!=null && UploadAbleDataConteiner.getDataContainer().getBeforImage().length > 0){// utils.writeInt(baOutputStream, 1);// utils.writeImage(baOutputStream, UploadAbleDataConteiner.getDataContainer().getBeforImage());// Log.i("BEFORE IMAGE TIME", "<><><>"+UploadAbleDataConteiner.getDataContainer().getBeforePictureTimeStamp());// utils.writeString(baOutputStream, UploadAbleDataConteiner.getDataContainer().getBeforePictureTimeStamp());// }else{// utils.writeInt(baOutputStream, 0);// }// if(UploadAbleDataConteiner.getDataContainer().getAfterImage()!=null && UploadAbleDataConteiner.getDataContainer().getAfterImage().length > 0){// utils.writeInt(baOutputStream, 1);// utils.writeImage(baOutputStream, UploadAbleDataConteiner.getDataContainer().getAfterImage());//imgAfter// Log.i("AFTER IMAGE TIME", "<><><>"+UploadAbleDataConteiner.getDataContainer().getAfterPictureTimeStamp());// utils.writeString(baOutputStream, UploadAbleDataConteiner.getDataContainer().getAfterPictureTimeStamp());// }else{// utils.writeInt(baOutputStream, 0);// } if(UploadAbleDataConteiner.getDataContainer().getShopImage()!=null && UploadAbleDataConteiner.getDataContainer().getShopImage().length>0){ utils.writeInt(baOutputStream, 1); utils.writeImage(baOutputStream,UploadAbleDataConteiner.getDataContainer().getShopImage()); utils.writeString(baOutputStream,UploadAbleDataConteiner.getDataContainer().getShopPictureTimeStamp()); }else{ utils.writeInt(baOutputStream, 0); } if(UploadAbleDataConteiner.getDataContainer().getImageDataVector() != null && !UploadAbleDataConteiner.getDataContainer().getImageDataVector().isEmpty()) { utils.writeInt(baOutputStream,UploadAbleDataConteiner.getDataContainer().getImageDataVector().size()); for(ImageData imageData:UploadAbleDataConteiner.getDataContainer().getImageDataVector()){ utils.writeInt(baOutputStream,Integer.parseInt(imageData.assetTypeId)); utils.writeString(baOutputStream,imageData.chillerVerificationCode); System.out.println("before picture timestamp===========================================>"+ imageData.chillerVerificationCode + ", " + imageData.assetTypeId); utils.writeInt(baOutputStream,Integer.parseInt(imageData.remarksId)); if(imageData.beforImage!=null && imageData.beforImage.length>0){ utils.writeInt(baOutputStream, 1); utils.writeImage(baOutputStream,imageData.beforImage); utils.writeString(baOutputStream,imageData.beforePictureTimeStamp); System.out.println("before picture timestamp===========================================>"+ imageData.beforePictureTimeStamp); }else{ utils.writeInt(baOutputStream, 0); } if(imageData.afterImage!=null && imageData.afterImage.length>0){ utils.writeInt(baOutputStream, 1); utils.writeImage(baOutputStream,imageData.afterImage); utils.writeString(baOutputStream,imageData.afterPictureTimeStamp); System.out.println("after picture timestamp===========================================>"+ imageData.afterPictureTimeStamp); }else{ utils.writeInt(baOutputStream, 0); } } } else { utils.writeInt(baOutputStream,0); } if(UploadAbleDataConteiner.getDataContainer().getTimeLogDataVector() != null && !UploadAbleDataConteiner.getDataContainer().getTimeLogDataVector().isEmpty()) { utils.writeInt(baOutputStream,UploadAbleDataConteiner.getDataContainer().getTimeLogDataVector().size()); for(TimeLog timeLog:UploadAbleDataConteiner.getDataContainer().getTimeLogDataVector()){ utils.writeString(baOutputStream,timeLog.getTimechanged()); } } else { utils.writeInt(baOutputStream,0); } Log.i("TOTAL PRODUCTS BEFOR UPLOADING", "<>"+Resources.getResources().getTotalUploadableProducts()); //product size if(!Resources.getResources().isSynchingProducts()){// Enumeration<String> e = UploadAbleDataConteiner.getDataContainer().getCategoryHolder().keys();// while(e.hasMoreElements()){// Vector<PruductsValues> v = UploadAbleDataConteiner.getDataContainer().getCategoryHolder().get(e.nextElement());// for(int j = 0; j<v.size(); j++){// Log.i("NOT SYNCHING PRODUCT ID", "#############################"+v.get(j).productId);// utils.writeInt(baOutputStream, Integer.parseInt(v.get(j).productId));//pid// utils.writeString(baOutputStream, v.get(j).availableValue);//available value//// // } Vector<Product> nonSyncProductList=DataHolder.getDataHolder().getNonSyncProductHashMap().get(UploadAbleDataConteiner.getDataContainer().getSelectedChannelId()); utils.writeInt(baOutputStream, nonSyncProductList.size()); for(Product product:nonSyncProductList){ utils.writeInt(baOutputStream, Integer.parseInt(product.productId));//pid utils.writeString(baOutputStream,"N");//available value } }else{ Resources.getResources().setSynchingProducts(false); Vector<PruductsValues> v = UploadAbleDataConteiner.getDataContainer().getSyncAbleProductDataVector(); utils.writeInt(baOutputStream, v.size()); for(int j = 0; j<v.size(); j++){ Log.i("PRODUCT ID", "#############################"+v.get(j).productId); utils.writeInt(baOutputStream, Integer.parseInt(v.get(j).productId));//pid utils.writeString(baOutputStream, v.get(j).availableValue);//available value } } boolean isPOPDataPresent = UserPreferences.getPreferences().getPOPDataPresent((Context)object); if(isPOPDataPresent) { DatabaseHandler db = new DatabaseHandler((Context)object); db.open(); POPsIssued pop = db.getPopIssued(UploadAbleDataConteiner.getDataContainer().getSelectedRootId()); db.close(); if(pop != null) { //pop data is present utils.writeInt(baOutputStream, 1); utils.writeInt(baOutputStream, pop.routeId); Log.i("PRODUCT ID", "route id for pops===================================>"+pop.routeId); utils.writeInt(baOutputStream, pop.posters); utils.writeInt(baOutputStream, pop.buntings); utils.writeInt(baOutputStream, pop.shelfTalkers); utils.writeInt(baOutputStream, pop.banners); } else { //pop data is not present utils.writeInt(baOutputStream, 0); } } else { //pop data is not present utils.writeInt(baOutputStream, 0); } Vector<ShopPOP> shopPOPVector=UploadAbleDataConteiner.getDataContainer().getShopPopVector(); if(shopPOPVector!=null){ for(ShopPOP pop:shopPOPVector){ if(pop.getBeforeImage()!=null){ utils.writeInt(baOutputStream,1); utils.writeImage(baOutputStream,pop.getBeforeImage()); utils.writeString(baOutputStream,pop.getBeforeTime()); }else{ utils.writeInt(baOutputStream,0); } if(pop.getAfterImage()!=null){ utils.writeInt(baOutputStream,1); utils.writeImage(baOutputStream,pop.getAfterImage()); utils.writeString(baOutputStream,pop.getAfterTime()); }else{ utils.writeInt(baOutputStream,0); } } }else{ utils.writeInt(baOutputStream,0); utils.writeInt(baOutputStream,0); } Vector<DisplayDrive> displayDriveVector=UploadAbleDataConteiner.getDataContainer().getDisplayDriveVector(); if(displayDriveVector!=null){ for(DisplayDrive drive:displayDriveVector){ utils.writeInt(baOutputStream,1); utils.writeString(baOutputStream,drive.getIsAvailable()); if(drive.getBeforeImage()!=null){ utils.writeInt(baOutputStream,1); utils.writeImage(baOutputStream,drive.getBeforeImage()); utils.writeString(baOutputStream,drive.getBeforeTime()); }else{ utils.writeInt(baOutputStream,0); } if(drive.getAfterImage()!=null){ utils.writeInt(baOutputStream,1); utils.writeImage(baOutputStream,drive.getAfterImage()); utils.writeString(baOutputStream,drive.getAfterTime()); }else{ utils.writeInt(baOutputStream,0); } } }else{ utils.writeInt(baOutputStream,0); } Vector<RetailerRemarks> retailRemarksVector=UploadAbleDataConteiner.getDataContainer().getRetailRemarksVector(); if(retailRemarksVector!=null){ utils.writeInt(baOutputStream,retailRemarksVector.size()); for(RetailerRemarks retailerRemarks:retailRemarksVector){ utils.writeInt(baOutputStream,Integer.parseInt(retailerRemarks.getRemarkId())); utils.writeString(baOutputStream,retailerRemarks.getRemarksAvailable()); } }else{ utils.writeInt(baOutputStream,0); } Vector<AssetTracking> assetTrackingVector=UploadAbleDataConteiner.getDataContainer().getAssetTrackingVector(); if(assetTrackingVector!=null){ utils.writeInt(baOutputStream,assetTrackingVector.size()); for(AssetTracking assetTracking:assetTrackingVector){ utils.writeInt(baOutputStream,Integer.parseInt(assetTracking.getRemarkId())); utils.writeString(baOutputStream,assetTracking.getRemarksAvailable()); } }else{ utils.writeInt(baOutputStream,0); } }else if(iJobCode==NetManger.MERCHANDISOR_SHOP_DATA){ utils.writeInt(baOutputStream,Integer.parseInt(this.param[0]));// user id utils.writeInt(baOutputStream,Integer.parseInt(this.param[1]));//root id }else if(iJobCode==NetManger.SUPERVISOR_UPLOAD_SHOP_DATA){//Supervisor Upload data utils.writeInt(baOutputStream,Integer.parseInt(this.param[0]));//sur id utils.writeInt(baOutputStream, Integer.parseInt(SuperUploadAbleDataConteiner.getDataContainer().getSelectedRootId()));//root id utils.writeInt(baOutputStream, Integer.parseInt(SuperUploadAbleDataConteiner.getDataContainer().getSelectedMerchandisorId()));//mer id utils.writeInt(baOutputStream, Integer.parseInt(SuperUploadAbleDataConteiner.getDataContainer().getSelectedShopId()));//shop id utils.writeInt(baOutputStream, SuperUploadAbleDataConteiner.getDataContainer().getRemarksId());// remark id utils.writeString(baOutputStream, SuperUploadAbleDataConteiner.getDataContainer().getShopTimeStamp());// time stamp if(SuperUploadAbleDataConteiner.getDataContainer().getShopImage()!=null && SuperUploadAbleDataConteiner.getDataContainer().getShopImage().length > 0){ utils.writeInt(baOutputStream, 1); utils.writeImage(baOutputStream, SuperUploadAbleDataConteiner.getDataContainer().getShopImage()); }else{ utils.writeInt(baOutputStream, 0); } } URL myurl = new URL(URL); urlConnection = (HttpURLConnection)myurl.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); /*urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); urlConnection.setRequestProperty("Accept", "application/octet-stream"); urlConnection.setRequestProperty("Content-Length", "xyz"); urlConnection.setRequestProperty("Connection", "close");*/ urlConnection.setRequestProperty("version", Utils.APPLICATION_CURRENT_VERSION+""); urlConnection.setRequestProperty("upc", UserPreferences.getPreferences().getUpdateRootCount((Context)object)+""); urlConnection.setConnectTimeout(60 * 1000); urlConnection.setReadTimeout(60 * 1000); urlConnection.connect(); outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); outputStream.write(baOutputStream.toByteArray()); outputStream.flush(); String upc = urlConnection.getHeaderField("upc"); Log.i("UPDATE COUNT", "<>>> "+upc); if(upc !=null && upc.length()>0){ Resources.getResources().setRootUpdateCount(Integer.parseInt(upc)); } String appServerSideVersion = urlConnection.getHeaderField("version"); if(appServerSideVersion!=null && appServerSideVersion.length()>0){// Log.i("SERVERSIDE VERSION", "<><>"+Integer.parseInt(appServerSideVersion)); Resources.getResources().setServersideApplicationVersion(appServerSideVersion); }else{ Log.i("TEMP VERSION", "00"); Resources.getResources().setServersideApplicationVersion("0"); } String alertMessage = urlConnection.getHeaderField("message"); if(alertMessage!=null && alertMessage.length()>0){ Log.i("ALERT MESSAGE", "<><>"+alertMessage); Resources.getResources().setUpdateApplicationAlert(alertMessage); } String updateAppUrl = urlConnection.getHeaderField("url"); if(updateAppUrl!=null && updateAppUrl.length()>0){ Log.i("APP URL", "<><>"+updateAppUrl); Resources.getResources().setUpdateAppUrl(updateAppUrl); } inputStream = new BufferedInputStream(urlConnection.getInputStream()); dataListener.dataArrived(object, inputStream); } catch (SecurityException se) { isExceptionOccured = true; Resources.alertTitle = "Error"; Resources.alertMessage = "Application not authorized to access internet." ; se.printStackTrace(); dataListener.cancleRequest(); Log.e("SE EXCEPTION", "EXCEPTION"); } catch (IOException ioe) { isExceptionOccured = true; Resources.alertTitle = "Error"; Resources.alertMessage = "GPRS connection not established. If problem persists please check your GPRS connectivity." ; ioe.printStackTrace(); dataListener.cancleRequest(); Log.e("IEO EXCEPTION", "EXCEPTION"); } catch (Exception e) { isExceptionOccured = true; Resources.alertTitle = "Error"; Resources.alertMessage = "GPRS connection not established. If problem persists please check your GPRS connectivity." ; e.printStackTrace(); dataListener.cancleRequest(); Log.e("EXCEPTION", "EXCEPTION"); } finally { try { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } if (urlConnection != null) { urlConnection.disconnect(); urlConnection = null; } } catch (Exception ex) { ex.printStackTrace(); } } return true; } @Override protected void onCancelled() { super.onCancelled(); Log.i("ON CANCEL EXECUTE", "<<<<ASYNC>>>>>"); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); pdialog.dismiss(); Log.i("ON POST EXECUTE", "<<ASYNC>>" + isExceptionOccured); if(!isExceptionOccured){ try { dataListener.dataParsed(); } catch (Exception e) { e.printStackTrace(); isExceptionOccured = false; Resources.getResources().showAlert((Context)object, "Error", "Network is not available, check your Network settings."); } }else{ isExceptionOccured = false; Resources.getResources().showAlert((Context)object, Resources.alertTitle, Resources.alertMessage); } } @Override protected void onPreExecute() { super.onPreExecute(); Context c = (Context)object; pdialog = new ProgressDialog(c); pdialog.setIcon(R.drawable.ic_launcher); pdialog.setTitle("Please Wait"); pdialog.setMessage("Working..."); if(dataListener instanceof RefreshProducts || dataListener instanceof RefreshRoots || dataListener instanceof UploadData){ pdialog.setCancelable(true); }else{ pdialog.setCancelable(false); } pdialog.show(); pdialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { Log.i("ON CANCEL LISTENER", "<<<<<<<<<<<>>>>>>>>>>>>>"); if(dataListener != null){ dataListener.cancleRequest(); } } }); }}=============package com.tcm.framework.utils;/** * ========================================= * Copyright Notice * This file contains proprietary information of Tricast Solutions Ltd * Copying or reproduction without prior written approval is prohibited * Copyright(c) 2006 - 2007 * ========================================= */import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.apache.log4j.Logger;// TODO: Auto-generated Javadoc/** * The Class CommunicationUtil. * * @author Muhammad Arif */public class CommunicationUtil { private static Logger logger = Logger.getLogger(CommunicationUtil.class); static final int buffSize =200*10; private byte[] imageBytes = null; int imageLength = 0; int pos = 0; int len = 0; byte chr[] = new byte[buffSize]; /** Return the individual Ads String value. */ private ResponseBuffer buffer = new ResponseBuffer(); /** The out stream. */ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); /** * Write string on stream. * * @param sText the s text * @throws IOException Signals that an I/O exception has occurred. */ public void write(String sText)throws IOException { CommunicationUtil.writeString(outStream, sText); buffer.append(sText); } /** * Write. * * @param nNumber the n number * @throws IOException Signals that an I/O exception has occurred. */ public void write(int nNumber) throws IOException { CommunicationUtil.writeInt(outStream, nNumber); buffer.append(nNumber); } /** * Write. * * @param imageBytes the image bytes * @throws IOException Signals that an I/O exception has occurred. */ public void write(byte[] imageBytes) throws IOException { writeInt(outStream, imageBytes.length); outStream.write(imageBytes); buffer.append(imageBytes); // here for buffer writing// response.getOutputStream().print("autumn_tcm");// outStream.write(imageBytes);// response.getOutputStream().print("autumn_tcm"); } /** * Terminate response. */ public void terminateResponse(){ try{ outStream.close(); }catch (Exception ex){ } } /** * Gets the response string. * * @return the response string */ public String getResponseString(){ return buffer.toString(); } /** * Gets the response byts. * * @return the response byts */ public byte[] getResponseByts(){ return outStream.toByteArray(); } /** * Write string. * * @param output the output * @param sText the s text * @throws IOException Signals that an I/O exception has occurred. */ public static void writeString(OutputStream output, String sText) throws IOException { int length = 0; if (sText == null || sText.length() == 0) { writeInt(output, length); } else { byte[] textBytes = sText.getBytes("UTF-8"); length = textBytes.length; writeInt(output, length); output.write(textBytes); } } /** * Return the individual Ads int value. * * @param output the OutputStream * @param nNumber the int value * @throws IOException Signals that an I/O exception has occurred. */ public static void writeInt(OutputStream output, int nNumber) throws IOException { byte[] numberBytes = intToByteArray(nNumber); output.write(numberBytes); } /** * Return the individual Ads Image. * * @param output the OutputStream * @param imageBytes the image bytes * @throws IOException Signals that an I/O exception has occurred. */ public static void writeImage(OutputStream output, byte[] imageBytes) throws IOException { writeInt(output, imageBytes.length); output.write(imageBytes); } /** * Convert int to byteArray. * * @param value the int value * @return byte[] the byte array */ private static byte[] intToByteArray(int value) { byte[] b = new byte[4]; for (int i = 0; i < 4; i++) { int offset = (b.length - 1 - i) * 8; b[i] = (byte) ((value >>> offset) & 0xFF); } return b; } /** * Read int from the InputStream. * @param is the InputStream * @return int the int value */ public int readInt(InputStream is) throws IOException { byte[] intBytes = new byte[4]; readFully(is, intBytes); int res = byteArrayToInt(intBytes); return res; } public String readString(InputStream is) throws IOException { String sText = null; int length = readInt(is); byte[] textBytes = new byte[length]; if (length != 0) { readFully(is, textBytes); } try { if (length == 0) { sText = ""; } else { sText = new String(textBytes, "UTF-8"); } } catch (Exception usee) { if (length == 0) { sText = ""; } else { sText = new String(textBytes); } logger.info("********************************"+sText); logger.info(stackTraceToString(usee)); } // System.out.println("readString :: " + sText); return sText; } /** * Read full of the byte data from the InputStream. * * @param is the InputStream * @param byteData the byte array used to store the data */ public void readFully(InputStream is, byte[] byteData) throws IOException { int needLength = byteData.length; int readCount = 0; while (true) { while (pos < len) { if (readCount == needLength) { return; } else { byteData[readCount] = chr[pos]; readCount++; pos++;// System.out.println("read count ==" + readCount);// System.out.println("position ==" + pos); } } try { len = is.read(chr, 0, chr.length);// logger.info("Data Recived **********************************"+new String(chr)); if (len == -1) { break; } } catch (Exception e) { break; } pos = 0; }// System.out.println("Inputstream length ::"+len); } /** * Read int from the ByteArrayInputStream. * @param is the ByteArrayInputStream * @return int the int value */ public int readInt(DataInputStream is) throws IOException { byte[] intBytes = new byte[4]; readFully(is, intBytes); return byteArrayToInt(intBytes); } /** * Read String from the ByteArrayInputStream * @param is the ByteArrayInputStream * @return String the String value */ public String readString(DataInputStream is) throws IOException { String sText = null; int length = readInt(is); byte[] textBytes = new byte[length]; if (length != 0) { readFully(is, textBytes); } try { sText = new String(textBytes, "UTF-8"); } catch (Exception usee) { sText = new String(textBytes); } return sText; } /** * Read full of the byte data from the ByteArrayInputStream. * @param is the ByteArrayInputStream * @param byteData the byte array used to store the data */ public void readFully(DataInputStream is, byte[] byteData) throws IOException { int needLength = byteData.length; int readCount = 0; while (true) { while (pos < len) { if (readCount == needLength) { return; } else { byteData[readCount] = chr[pos]; readCount++; pos++; } } len = is.read(chr, 0, chr.length); if (len == -1) { break; } pos = 0; } } public static int byteArrayToInt(byte[] byteArray) { return byteArrayToInt(byteArray, 0); } public static int byteArrayToInt(byte[] byteArray, int offset) { int value = 0; for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (byteArray[i + offset] & 0x000000FF) << shift; } return value; } public byte[] readImage(InputStream is){ try { imageLength = readInt(is); // logger.info("Image Lenght = "+imageLength); imageBytes = new byte[imageLength]; if (imageLength != 0) { readFully(is, imageBytes); } } catch (IOException e) { e.printStackTrace(); } return imageBytes; } public String stackTraceToString(Throwable e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement element : e.getStackTrace()) { sb.append(element.toString()); sb.append("\n"); } return sb.toString(); }}// End of Class