Search code examples
javamultithreadingstruts

Request parameters coming from jsps are changed when two different users access the code same time


public String generateDataPDF() {
    System.out.println("Inside generate PDF");
    String filePath = "";
    HttpSession sess = ServletActionContext.getRequest().getSession();
    try {


        sess.setAttribute("msg", "");
        if (getCrnListType().equalsIgnoreCase("F")) {
            try {
                filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
                System.out.println("File stored  path : " + filePath);
                target = new File(filePath);
                FileUtils.copyFile(crnFile, target);
            } catch (Exception e) {
                System.out.println("File path Exception " + e);
            }
        }


        System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
                + " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());

        String srtVAL = "";

        String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
            getOutputPath(), getGenMode(), getRenType()};

        //INS DB Connection
        con = getInsjdbcConnection();

        ArrayList selectedCRNList = new ArrayList();
        String selectedCRNStr = "";
        selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);

        String[] fileRes = selectedCRNStr.split("\\,");
        if (fileRes[0].equalsIgnoreCase("FAIL")) {
            System.out.println("fileRes is FAIL beacause of other extension file.");
            sess.setAttribute("pr", "Please upload xls or csv file.");
            return SUCCESS;
        }

        System.out.println("List file is : " + selectedCRNStr);

        String st[] = srtVAL.split("[*]");
        String billDateStr = DateUtil.getStrDateProc(new Date());
        Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
        String minAMPM = DateUtil.getTimeDate(new Date());
        String str = "";
        String batchID = callSequence();
        try {

            System.out.println("Inside Multiple policy Generation.");
            String userName=sess.getAttribute("loginName").toString();
            String list = getProcessesdList(userName);
            if (list != null) {
                System.out.println("list is not null Users previous data is processing.....");
                //setTotalPDFgNERATEDmSG("Data is processing please wait.");
                sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
                return SUCCESS;
            }

            String[] policyNo = selectedCRNStr.split("\\,");

            int l = 0, f = 0,counter=1;
            for (int j = 0; j < policyNo.length; j++,counter++) {

                String pdfFileName = "";
                int uniqueId=counter;
                globUniqueId=uniqueId;
                insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);

                System.out.println("Executing Proc one by one.");
                System.out.println("policyNo[j]" + policyNo[j]);
                System.out.println("getOptionId()" + getOptionId());
                System.out.println("seqValue i.e batchId : " + batchID);
             }
                  str = callProcedure(policyNo[j], getOptionId(), batchID);
                String[] procResponse = str.split("\\|");
                for (int i = 0; i < procResponse.length; i++) {
                    System.out.println("Response is : " + procResponse[i]);
                }

                if (procResponse[0].equals("SUCCESS")) {
                    Generator gen = new Generator();

                    if (getPdfName().equalsIgnoreCase("true")) {
                        System.out.println("Checkbox is click i.e true");
                        pdfFileName = procResponse[1];
                    } else {
                        System.out.println("Checkbox is not click i.e false");
                        String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
                        String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
                        if (getLogoType().equals("0") || getLogoType().equals("2")) {
                            System.out.println("If logo is O or 1");
                            pdfFileName = fileName[1];
                        } else if (getLogoType().equals("1")) {
                            System.out.println("If logo is 2");
                            pdfFileName = fileName[0];
                        }

                    }

                    b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
                    l++;
                    updateData(uniqueId,batchID, "Y");
                } else {
                    f++;
                    updateData(uniqueId,batchID, "F");
                }

            }        
            sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
        }catch (Exception e) {
            updateData(globUniqueId,batchID, "F");
            System.out.println("Exception in procedure call");
            setTotalPDFgNERATEDmSG("Fail");
            e.printStackTrace();
            sess.setAttribute("pr", "Server Error.");
            return SUCCESS;
        }
    }catch (Exception ex) {
        ex.printStackTrace();
        sess.setAttribute("pr", "Server Error.");
        return SUCCESS;
    }
    System.out.println("Above second return");
    return SUCCESS;
}

GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?


Solution

  • As per your comment, this is what I would do, It's probably not the best way to do !

    Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.

    Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)

    "Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.

    NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.

    Thus, your code should be refactored a little bit.