public static void initializeCyberplateETransaction(
     TransactionTransportBean transactionTransportBean) {
   if (flag) {
     if (transactionTransportBean != null) {
       int pubkeys = 0;
       if (transactionTransportBean.getToken3() != null) {
         pubkeys = Integer.parseInt(transactionTransportBean.getToken3());
       }
       try {
         CyberPlateIntegrationUtil.init(
             transactionTransportBean.getToken(),
             transactionTransportBean.getToken1(),
             transactionTransportBean.getToken2(),
             pubkeys);
       } catch (Exception e) {
         flag = true;
         e.printStackTrace();
       }
     }
     flag = false;
   }
 }
  private StringBuilder moneyTransferUserRegistration(
      StringBuilder data, TransactionTransportBean bean) {
    data.append("emailId=").append(bean.getiCashRecharge().getEmailId()).append("\n");
    data.append("amountsend=").append("1.00").append("\n");
    SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy");
    data.append("pinCode=").append(sd.format(bean.getPinNumber())).append("\n");
    data.append("middleName=").append(bean.getiCashRecharge().getMiddleName()).append("\n");
    data.append("amount=").append("0.00").append("\n");
    data.append("NUMBER=").append(bean.getMobileNo()).append("\n");
    data.append("dop_kom=").append("0.00").append("\n");
    data.append("lastName=").append(bean.getiCashRecharge().getLastName()).append("\n");
    data.append("dateOfBirth=").append(bean.getiCashRecharge().getDateOfBirth()).append("\n");
    data.append("firstName=").append(bean.getiCashRecharge().getUserName()).append("\n");

    return data;
  }
  public void doTransaction(TransactionTransportBean transportBean) throws MalformedURLException {
    initializeCyberplateETransaction(transportBean);
    String finalData = null;
    try {
      finalData = getDataFromThirdParty(transportBean);
      // System.out.println("final data of getdata from thirdparty"
      // + finalData);
    } catch (ThirdPartyRechargeCallException e) {
      e.printStackTrace();
      transportBean.setMessage(
          "Transaction pending from thirdparty: ThirdPartyRechargeCallException");
      return;
    } catch (Exception e) {
      e.printStackTrace();
      if (e instanceof MalformedURLException) throw (MalformedURLException) e;
      transportBean.setMessage("Transaction pending from thirdparty");
      return;
    }
    if (finalData != null && !finalData.startsWith("PROBLEM")) {
      Map<String, String> dataMap = parseResponse(finalData);

      // System.out.println("parsed data" + dataMap.size() + dataMap);
      String errorValue = dataMap.get("ERROR");
      String resultVal = dataMap.get("RESULT");

      if (!"0".equals(errorValue) || !"0".equals(resultVal)) {

        try {
          transportBean.setErrorCode(2);
        } catch (Exception e) {
          e.printStackTrace();
          transportBean.setErrorCode(2);
        }
        transportBean.setErrorcode(errorValue);
        transportBean.setMessage("Error " + errorValue);
        transportBean.setErrorMessage("Error " + errorValue);

      } else if ("0".equals(errorValue) && "0".equals(resultVal)) {
        transportBean.setThirdpartytransid(dataMap.get("TRANSID"));

        StringBuffer values = new StringBuffer();
        values.append(dataMap.get("SESSION"));
        if (dataMap.get("AUTHCODE") != null) {
          values.append(":").append(dataMap.get("AUTHCODE"));
        }
        transportBean.setResponsecode(values.toString());
        if (!transportBean.getMessage().contains("Your card has been credited by")) {
          transportBean.setMessage("Transaction Successful");
        }

        transportBean.setThirdPartyTransDateTime(dataMap.get("DATE"));
      }
    }
  }
  private StringBuilder iCashRechargeUrl(StringBuilder data, TransactionTransportBean bean) {
    data.append("USERNAME="******"\n");
    if (bean.getiCashRecharge().getDocumentDetail() != null) {
      data.append("PROOFDOCUMENTDETAILS=")
          .append(bean.getiCashRecharge().getDocumentDetail())
          .append("\n");
    } else {
      data.append("PROOFDOCUMENTDETAILS=").append("NA").append("\n");
    }

    SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy");
    data.append("USERDATEOFBIRTH=")
        .append(sd.format(bean.getiCashRecharge().getDateOfBirth()))
        .append("\n");
    data.append("USERADDRESS=").append(bean.getiCashRecharge().getAddress()).append("\n");
    if (bean.getiCashRecharge().getDocumentType() != null) {
      data.append("PROOFDOCUMENTTYPE=")
          .append(bean.getiCashRecharge().getDocumentType())
          .append("\n");
    } else {
      data.append("PROOFDOCUMENTTYPE=").append("NA").append("\n");
    }

    data.append("USERSTATE=").append(bean.getiCashRecharge().getState()).append("\n");
    data.append("USEREMAILID=").append(bean.getiCashRecharge().getEmailId()).append("\n");
    data.append("USERMOTHERSMAIDENNAME=")
        .append(bean.getiCashRecharge().getMotherName())
        .append("\n");
    data.append("USERLASTNAME=").append(bean.getiCashRecharge().getLastName()).append("\n");
    data.append("USERMIDDLENAME=").append(bean.getiCashRecharge().getMiddleName()).append("\n");
    data.append("NUMBER=").append(bean.getMobileNo()).append("\n");
    // Here amount for icash registration will be always 1.00
    data.append("AMOUNT=").append("1.00").append("\n");
    data.append("AMOUNT_ALL=").append("1.00").append("\n");
    data.append("COMMENT=").append(bean.getiCashRecharge().getComment()).append("\n");

    return data;
  }
  private String inputMessageCreation(
      TransactionTransportBean transactionTransport,
      StringBuilder sessionVal,
      boolean isCommentRequired)
      throws Exception, UnsupportedEncodingException {
    String finalInput;
    // System.out.println("sessionVal=" + sessionVal);
    StringBuilder inputMessageTemp = new StringBuilder();
    String data = transactionTransport.getAgentId();
    ArrayList<String> list = new ArrayList<String>();
    if (data != null) {
      StringTokenizer stringTokenizer = new StringTokenizer(data, ":");
      while (stringTokenizer.hasMoreTokens()) {
        list.add(stringTokenizer.nextToken());
      }
    }

    inputMessageTemp.append("SD=").append(list.get(0)).append("\n");
    inputMessageTemp.append("AP=").append(list.get(1)).append("\n");
    inputMessageTemp.append("OP=").append(list.get(2)).append("\n");
    inputMessageTemp.append("SESSION=").append(sessionVal).append("\n");
    if (transactionTransport.getTransactionName().equals("ELECTRICITY")) {
      if (transactionTransport.getOperator().equals("Reliance Energy Limited - MUMBAI")) {
        inputMessageTemp
            .append("NUMBER=")
            .append(transactionTransport.getConnectionid())
            .append("\n");
        inputMessageTemp
            .append("ACCOUNT=")
            .append(transactionTransport.getCycleNumber())
            .append("\n");
      } else {
        inputMessageTemp
            .append("NUMBER=")
            .append(transactionTransport.getConnectionid())
            .append("\n");
        inputMessageTemp.append("ACCOUNT=").append("\n");
      }
      inputMessageTemp
          .append("AMOUNT=")
          .append(twoDecimalPlaceNumber(transactionTransport.getAmount()))
          .append("\n");

    } else if (transactionTransport.getTransactionName().equals("LANDLINE")) {
      if (transactionTransport.getOperator().equals("MTNL All India")) {
        inputMessageTemp
            .append("NUMBER=")
            .append(transactionTransport.getConnectionid())
            .append("\n");
        inputMessageTemp.append("ACCOUNT=").append(transactionTransport.getCanumber()).append("\n");

      } else {
        inputMessageTemp
            .append("NUMBER=")
            .append(transactionTransport.getConnectionid())
            .append("\n");
        inputMessageTemp.append("ACCOUNT=").append("\n");
      }
      inputMessageTemp
          .append("AMOUNT=")
          .append(twoDecimalPlaceNumber(transactionTransport.getAmount()))
          .append("\n");

    } else if (transactionTransport.getTransactionName().equals("INSURANCE_BILL")) {
      inputMessageTemp
          .append("NUMBER=")
          .append(transactionTransport.getConnectionid())
          .append("\n");
      inputMessageTemp.append("ACCOUNT=").append(transactionTransport.getDob()).append("\n");
      inputMessageTemp
          .append("AMOUNT=")
          .append(twoDecimalPlaceNumber(transactionTransport.getAmount()))
          .append("\n");
    } else if (transactionTransport.getTransactionName().equals("MOBILE_RECHARGE")) {
      inputMessageTemp.append("NUMBER=").append(transactionTransport.getMobileNo()).append("\n");
      inputMessageTemp.append("ACCOUNT=").append("\n");
      inputMessageTemp
          .append("AMOUNT=")
          .append(transactionTransport.getAmount())
          .append("\n"); // transactionTransport.getAmount()

    } else if (transactionTransport.getTransactionName().equals("ICASH_RECHARGE")) {

      iCashRechargeUrl(inputMessageTemp, transactionTransport);
      isCommentRequired = false;

    } else if (transactionTransport.getTransactionName().equals("ICASH_CARD_RECHARGE")) {
      inputMessageTemp.append("NUMBER=").append(transactionTransport.getMobileNo()).append("\n");
      inputMessageTemp
          .append("CARDNO=")
          .append(transactionTransport.getiCashRecharge().getDocumentDetail())
          .append("\n");
      inputMessageTemp
          .append("AMOUNT=")
          .append(CyberTelUtil.twoDecimalPlaceNumber(transactionTransport.getAmount()))
          .append("\n");
      inputMessageTemp
          .append("AMOUNT_ALL=")
          .append(
              CyberTelUtil.twoDecimalPlaceNumber(
                  transactionTransport.getiCashRecharge().getAmountAll()))
          .append("\n");
      inputMessageTemp
          .append("COMMENT=")
          .append(transactionTransport.getiCashRecharge().getComment())
          .append("\n");
      isCommentRequired = false;

    } else if (transactionTransport.getTransactionName().equals("OTP_NUMBER")) {
      moneyTransferOTPNumber(inputMessageTemp, transactionTransport);
    } else if (transactionTransport
        .getTransactionName()
        .equals("MONEY_TRANSFER_USER_REGISTRATION")) {
      moneyTransferUserRegistration(inputMessageTemp, transactionTransport);
    } else if (transactionTransport.getTransactionName().equals("ADD_BANK_DETAIL")) {
      moneyTransferAddBankDetail(inputMessageTemp, transactionTransport);
    } else if (transactionTransport.getTransactionName().equals("GET_BANK_DETAIL")) {
      moneyTransferGetBankDetail(inputMessageTemp, transactionTransport);
    } else if (transactionTransport.getTransactionName().equals("REMITTANCE")) {
      moneyTransferRemittance(inputMessageTemp, transactionTransport);
    } else {
      inputMessageTemp
          .append("NUMBER=")
          .append(transactionTransport.getConnectionid())
          .append("\n");
      inputMessageTemp.append("ACCOUNT=").append("\n");
      if (transactionTransport.getTransactionName().equals("DTH_RECHARGE")
          || transactionTransport.getTransactionName().equals("DATACARD_RECHARGE")) {
        inputMessageTemp
            .append("AMOUNT=")
            .append(transactionTransport.getAmount())
            .append("\n"); // transactionTransport.getAmount()
      } else {
        inputMessageTemp
            .append("AMOUNT=")
            .append(twoDecimalPlaceNumber(transactionTransport.getAmount()))
            .append("\n");
      }
    }

    if (isCommentRequired) {

      inputMessageTemp
          .append("COMMENT=")
          .append("Retailer " + transactionTransport.getFranchiseeMobileNum())
          .append("\n");
    }

    // System.out.println("Before sign in finalInput "
    // + inputMessageTemp.toString());

    finalInput = CyberPlateIntegrationUtil.signMessage(inputMessageTemp.toString());
    // System.out.println("After Signing finalInput=" + finalInput);
    finalInput = URLEncoder.encode(finalInput, "UTF-8");
    // System.out.println("After Encoding finalInput=" + finalInput);

    finalInput = "inputmessage=" + finalInput;
    return finalInput;
  }
  private String getDataFromThirdParty(TransactionTransportBean transactionTransport)
      throws Exception {

    String finalInput = null;

    StringBuilder sessionVal = new StringBuilder(transactionTransport.getRetailerId());
    int length = transactionTransport.getRetailerId().length();
    if (length < 10) {
      for (int i = 0; i < 8 - transactionTransport.getRetailerId().length(); i++) {
        sessionVal.append("0");
      }
    }

    String operatorCode = transactionTransport.getOperatorCode();
    String connectURL[] = new String[2];
    if (operatorCode != null) {
      StringTokenizer stringTokenizer = new StringTokenizer(operatorCode, ";");
      int index = 0;
      while (stringTokenizer.hasMoreTokens()) {
        connectURL[index] = stringTokenizer.nextToken();
        index++;
      }
    }
    if (connectURL.length > 1) {
      sessionVal.append(transactionTransport.getTransid().substring(13));
      finalInput = inputMessageCreation(transactionTransport, sessionVal, true);
      String outputMessage = getDataFromURL(connectURL[0], finalInput);
      // System.out.println("outputMessage getDataFromThirdParty "
      // + outputMessage);
      int errorIndex = outputMessage.indexOf("ERROR=");
      int resultIndex = outputMessage.indexOf("RESULT=");
      // System.out.println("resultIndex>" + resultIndex);
      String errorVal = "1";
      String resultVal = "1";
      if (errorIndex != -1 && resultIndex != -1) {
        errorVal = outputMessage.substring(errorIndex + 6, errorIndex + 8);
        resultVal = outputMessage.substring(resultIndex + 7, resultIndex + 9);
        // System.out.println("resulVal:> " + resultVal);
      }

      if ((resultVal != null && "0".equals(resultVal.trim()))
          && (errorVal != null && "0".equals(errorVal.trim()))) {
        transactionTransport.setConnectURL(connectURL[1]);

        finalInput = inputMessageCreation(transactionTransport, sessionVal, false);
        outputMessage = getDataFromURL(transactionTransport.getConnectURL(), finalInput);
        // System.out.println("outputMessage:::" + outputMessage);
        String[] line = outputMessage.split("\n");
        String addInfo = "";
        for (String info : line) {
          if (info.contains("ADDINFO=")) {
            addInfo = info.substring(8);
            break;
          }
        }
        transactionTransport.setMessage(addInfo);

      } else {
        transactionTransport.setErrorCode(2);
        transactionTransport.setErrorcode(errorVal);
        transactionTransport.setMessage("Error " + errorVal);
        transactionTransport.setErrorMessage("Error " + errorVal);
        // System.out.println("errore code"
        // + transactionTransport.getErrorcode() + "message"
        // + transactionTransport.getMessage());
        return "PROBLEM:" + errorVal;
      }
      return outputMessage;
    }
    return "PROBLEM:Operator Setup Error";
  }
  @RequestMapping(value = "/rechargedetail", method = RequestMethod.POST)
  public String rechargeDetail(
      @ModelAttribute("telecomrecharge") TransactionTransportBean transactionTransport,
      /* @RequestParam Long uuid, */ ModelMap model,
      HttpServletRequest req) {
    HttpSession session = req.getSession();
    String pathToFollow = null;
    Long suuid = (Long) session.getAttribute("suuid");
    if (suuid != null) {
      session.setAttribute("suuid", null);
      session.setAttribute("rechargeType", transactionTransport.getRechargeType());
      session.setAttribute("circle", transactionTransport.getCircleName());
      session.setAttribute("mobileNo", transactionTransport.getMobileNo());
      session.setAttribute(
          "amount", CyberTelUtil.removeDecimalFromNumber(transactionTransport.getAmount()));
      session.setAttribute("operator", transactionTransport.getOperator());

      transactionTransport.setRetailerId((String) req.getSession().getAttribute("userid"));
      transactionTransport.setTransactionName("MOBILE_RECHARGE");
      transactionTransport.setFranchiseeMobileNum((String) session.getAttribute("userName"));
      try {
        rechargeTransactionService.doRechargeService(transactionTransport);
      } catch (Exception e) {
        e.printStackTrace();
        transactionTransport.setMessage("System Error");
        // transactionTransport.setErrorCode(3);
      }

      if (transactionTransport.getErrorCode() > 0
          || transactionTransport.getThirdpartytransid() == null) {
        String errorMsg = "Error in Transaction</br>";
        if (transactionTransport.getMessage() != null) {
          errorMsg += transactionTransport.getMessage();
        }
        model.addAttribute("Error", errorMsg);
        model.addAttribute("telecomrecharge", transactionTransport);
        pathToFollow = "telecomRechargeFran";
      } else {
        session.setAttribute("transId", transactionTransport.getTransid());
        // SimpleDateFormat sdf = new
        // SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
        session.setAttribute("datetime", transactionTransport.getThirdPartyTransDateTime());
        // model.addAttribute("datetime",
        // sdf.format(transactionTransport.getCreatedAt()));

        String userId = (String) session.getAttribute("userid");
        FranchiseeInfo franchiseeInfo = franchiseeInfoService.getFranchiseeInfo(userId);
        session.setAttribute("franchiseeInfo", franchiseeInfo);

        pathToFollow = "redirect:rechargedetailfran";
      }
    } else {
    }
    return pathToFollow;
  }