Example usage for java.lang RuntimeException printStackTrace

List of usage examples for java.lang RuntimeException printStackTrace

Introduction

In this page you can find the example usage for java.lang RuntimeException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public String edaAction() {

    //        dbgLog.fine("selected tab(eda)="+getTabSet1().getSelected());
    // clear the error message around the EDA button if they exisit
    resetMsgEdaButton();//w  w  w . ja v  a  2s . co m

    if (checkEdaParameters()) {

        FacesContext cntxt = FacesContext.getCurrentInstance();

        HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse();
        HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest();

        dbgLog.info("***** within edaAction() *****");

        StudyFile sf = dataTable.getStudyFile();
        Long noRecords = dataTable.getRecordsPerCase();

        String dsbUrl = getDsbUrl();
        dbgLog.info("dsbUrl=" + dsbUrl);

        String serverPrefix = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();
        /*
        String serverPrefix = "http://dvn-alpha.hmdc.harvard.edu"
            + req.getContextPath();
        */
        dbgLog.info("serverPrefix" + serverPrefix);

        /*
         * "optnlst_a" => "A01|A02|A03",
         * "analysis" => "A01 A02",
         * "varbl" => "v1.3 v1.10 v1.13 v1.22 v1.40", 
         * "charVarNoSet" =>
         * "v1.10|v1.719",
         */

        Map<String, List<String>> mpl = new HashMap<String, List<String>>();

        Object[] vs = edaOptionSet.getSelectedValues();
        // analysis=[A01, A02]
        List<String> alst = new ArrayList<String>();

        for (int i = 0; i < vs.length; i++) {
            dbgLog.info("eda option[" + i + "]=" + vs[i]);
            alst.add((String) vs[i]);
        }

        mpl.put("analysis", alst);

        mpl.put("optnlst_a", Arrays.asList("A01|A02|A03"));

        // if there is a user-defined (recoded) variables
        /*
        if (recodedVarSet.size() > 0) {
            mpl.putAll(getRecodedVarParameters());
        }
        */
        //                dbgLog.fine("citation info to be sent:\n" + citation);
        //                mpl.put("OfflineCitation", Arrays.asList(citation));
        //                mpl.put("appSERVER", Arrays.asList(req.getServerName() + ":"
        //                    + req.getServerPort() + req.getContextPath()));

        mpl.put("studytitle", Arrays.asList(getStudyTitle()));
        dbgLog.info("studyId from get method=" + getStudyId().toString());
        mpl.put("studyno", Arrays.asList(getStudyId().toString()));
        mpl.put("studyURL", Arrays.asList(studyURL));
        mpl.put("browserType", Arrays.asList(browserType));

        mpl.put("recodedVarIdSet", getRecodedVarIdSet());
        mpl.put("recodedVarNameSet", getRecodedVarNameSet());
        mpl.put("recodedVarLabelSet", getRecodedVarLabelSet());
        mpl.put("recodedVarTypeSet", getRecodedVariableType());
        mpl.put("recodedVarBaseTypeSet", getBaseVariableTypeForRecodedVariable());

        mpl.put("baseVarIdSet", getBaseVarIdSetFromRecodedVarIdSet());
        mpl.put("baseVarNameSet", getBaseVarNameSetFromRecodedVarIdSet());

        mpl.put("requestType", Arrays.asList("EDA"));

        // -----------------------------------------------------
        // New processing route
        // 
        // Step 0. Locate the data file and its attributes

        String fileId = sf.getId().toString();
        //VDC vdc = vdcService.getVDCFromRequest(req);

        String fileloc = sf.getFileSystemLocation();
        String tabflnm = sf.getFileName();
        boolean sbstOK = sf.isSubsettable();
        String flct = sf.getFileType();

        dbgLog.info("location=" + fileloc);
        dbgLog.info("filename=" + tabflnm);
        dbgLog.info("subsettable=" + sbstOK);
        dbgLog.info("filetype=" + flct);

        DvnRJobRequest sro = null;

        List<File> zipFileList = new ArrayList();

        // the data file for downloading/statistical analyses must be subset-ready
        // local (relative to the application) file case 
        // note: a typical remote case is: US Census Bureau
        File tmpsbfl = null;
        if (sbstOK) {

            try {
                // this temp file will store the requested columns:
                tmpsbfl = File.createTempFile("tempsubsetfile.", ".tab");
                deleteTempFileList.add(tmpsbfl);

                // to produce this file, we'll either open the stream
                // and run our local subsetting code on it, or request
                // the subsetting to be performed natively by the access
                // driver, if it supports the functionality:

                // check whether a source file is tab-delimited or not

                boolean fieldcut = true;
                if ((noRecords != null) && (noRecords >= 1)) {
                    fieldcut = false;
                }

                DataAccessRequest daReq = new DataAccessRequest();
                daReq.setParameter("noVarHeader", "1");

                DataAccessObject accessObject = DataAccess.createDataAccessObject(sf, daReq);

                if (accessObject.isSubsetSupported()) {
                    dbgLog.info("Using NATIVE subset functionality of the repository.");
                    daReq.setParameter("vars", getVariableNamesForSubset());

                    accessObject.open();

                    InputStream inSubset = accessObject.getInputStream();
                    OutputStream outSubset = new BufferedOutputStream(
                            new FileOutputStream(tmpsbfl.getAbsolutePath()));

                    int bufsize = 8192;
                    byte[] subsetDataBuffer = new byte[bufsize];
                    while ((bufsize = inSubset.read(subsetDataBuffer)) != -1) {
                        outSubset.write(subsetDataBuffer, 0, bufsize);
                    }

                    inSubset.close();
                    outSubset.close();

                    // TODO: catch exceptions; reset the state of the page
                    // if anything went wrong. See the fixed-field section
                    // below for an example.

                } else {
                    accessObject.open();

                    if (fieldcut) {
                        // Cutting requested fields of data from a TAB-delimited stream:

                        Set<Integer> fields = getFieldNumbersForSubsetting();
                        dbgLog.info("subsetting fields=" + fields);

                        // Create an instance of DvnJavaFieldCutter
                        FieldCutter fc = new DvnJavaFieldCutter();

                        // Executes the subsetting request
                        fc.subsetFile(accessObject.getInputStream(), tmpsbfl.getAbsolutePath(), fields,
                                dataTable.getCaseQuantity(), "\t");

                        // TODO: catch exceptions; reset the state of the page
                        // if anything went wrong. See the fixed-field section
                        // below for an example.

                    } else {
                        // Cutting requested columns of data from a fixed-field stream:

                        Map<Long, List<List<Integer>>> varMetaSet = getSubsettingMetaData(noRecords);
                        DvnNewJavaFieldCutter fc = new DvnNewJavaFieldCutter(varMetaSet);

                        try {
                            //fc.cutColumns(new File(cutOp1), noRecords.intValue(), 0, "\t", tmpsbfl.getAbsolutePath());
                            fc.cutColumns(accessObject.getInputStream(), noRecords.intValue(), 0, "\t",
                                    tmpsbfl.getAbsolutePath());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an IO problem");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        } catch (RuntimeException re) {
                            re.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an runtime error");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an runtime error");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        }

                    }
                }

                // Checks the resulting subset file 
                if (tmpsbfl.exists()) {
                    Long subsetFileSize = tmpsbfl.length();
                    dbgLog.info("subsettFile:Length=" + subsetFileSize);
                    dbgLog.info("tmpsb file name=" + tmpsbfl.getAbsolutePath());

                    if (subsetFileSize > 0) {
                        mpl.put("subsetFileName", Arrays.asList(tmpsbfl.getAbsolutePath()));
                        mpl.put("subsetDataFileName", Arrays.asList(tmpsbfl.getName()));
                    } else {
                        // subset file exists but it is empty

                        msgEdaButton.setValue("* an subset file is empty");
                        msgEdaButton.setVisible(true);
                        dbgLog.warning(
                                "exiting edaAction() due to a subsetting error:" + "a subset file is empty");
                        getVDCRequestBean().setSelectedTab("tabEda");

                        return "";

                    }
                } else {
                    // subset file was not created
                    msgEdaButton.setValue("* a subset file was not created");
                    msgEdaButton.setVisible(true);
                    dbgLog.warning(
                            "exiting edaAction() due to a subsetting error:" + "a subset file was not created");
                    getVDCRequestBean().setSelectedTab("tabEda");

                    return "";

                }

                // Step 3. Organizes parameters/metadata to be sent to the implemented
                // data-analysis-service class

                //Map<String, Map<String, String>> vls = getValueTableForRequestedVariables(getDataVariableForRequest());
                Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables();

                sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema);

                //                    dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE));

                // Step 4. Creates an instance of the the implemented 
                // data-analysis-service class 

                DvnRDataAnalysisServiceImpl das = new DvnRDataAnalysisServiceImpl();

                // Executes a request of downloading or data analysis and 
                // capture result info as a Map <String, String>

                resultInfo = das.execute(sro);

                // Step 5. Checks the DSB-exit-status code
                if (resultInfo.get("RexecError").equals("true")) {
                    msgEdaButton.setValue("* The Request failed due to an R-runtime error");
                    msgEdaButton.setVisible(true);
                    dbgLog.info("exiting edaAction() due to an R-runtime error");
                    getVDCRequestBean().setSelectedTab("tabEda");

                    return "";
                } else {
                    if (recodeSchema.size() > 0) {
                        resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation());
                    } else {
                        resultInfo.put("subsettingCriteria", "");
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();

                msgEdaButton.setValue("* file URL is malformed");
                msgEdaButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to a URL problem ");
                getVDCRequestBean().setSelectedTab("tabEda");

                return "";

            } catch (IOException e) {
                // this may occur if the dataverse is not released
                // the file exists, but it is not accessible 
                e.printStackTrace();

                msgEdaButton.setValue("* an IO problem occurred");
                msgEdaButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabEda");

                return "";
            }

            // end of the subset-OK case
        } else {
            // not subsettable data file
            msgEdaButton.setValue("* this data file is not subsettable file");
            msgEdaButton.setVisible(true);
            dbgLog.warning("exiting edaAction(): the data file is not subsettable ");
            getVDCRequestBean().setSelectedTab("tabEda");

            return "";

        } // end:subsetNotOKcaseF

        // final processing steps for all successful cases

        resultInfo.put("offlineCitation", getCitation());
        resultInfo.put("studyTitle", getStudyTitle());
        resultInfo.put("studyNo", getStudyId().toString());
        resultInfo.put("fileName", fileName);
        resultInfo.put("dtId", dtId.toString());
        if (versionNumber != null) {
            resultInfo.put("versionNumber", versionNumber.toString());
        }
        resultInfo.put("studyURL", studyURL);
        resultInfo.put("R_min_verion_no", resultInfo.get("Rversion").substring(2));
        resultInfo.put("dataverse_version_no", dvnVersionNumber);

        dbgLog.info("RwrkspFileName=" + resultInfo.get("wrkspFileName"));

        // writing necessary files
        try {

            // rename the subsetting file
            File tmpsbflnew = File.createTempFile(SUBSET_FILENAME_PREFIX + resultInfo.get("PID") + ".", ".tab");
            deleteTempFileList.add(tmpsbflnew);
            InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl));
            OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew));

            int bufsize;
            byte[] bffr = new byte[8192];
            while ((bufsize = inb.read(bffr)) != -1) {
                outb.write(bffr, 0, bufsize);
            }
            inb.close();
            outb.close();

            String rhistNew = StringUtils.replace(resultInfo.get("RCommandHistory"), tmpsbfl.getName(),
                    tmpsbflnew.getName());

            //zipFileList.add(tmpsbflnew);

            // (1) write a citation file 
            //                String citationFilePrefix = "citationFile_"+ resultInfo.get("PID") + "_";
            //                File tmpcfl = File.createTempFile(citationFilePrefix, ".txt");
            //
            //                zipFileList.add(tmpcfl);
            //                deleteTempFileList.add(tmpcfl);
            //
            //                DvnCitationFileWriter dcfw = new DvnCitationFileWriter(resultInfo);
            //
            //                String fmpcflFullname = tmpcfl.getAbsolutePath();
            //                String fmpcflname = tmpcfl.getName();
            //                dcfw.write(tmpcfl);

            // (2) R command file
            String rhistoryFilePrefix = R_COMMAND_FILE_PREFIX + resultInfo.get("PID") + ".R";
            File tmpRhfl = new File(TEMP_DIR, rhistoryFilePrefix);

            zipFileList.add(tmpRhfl);
            deleteTempFileList.add(tmpRhfl);
            resultInfo.put("dvn_R_helper_file", "dvn_helper.R");
            DvnReplicationCodeFileWriter rcfw = new DvnReplicationCodeFileWriter(resultInfo);
            rcfw.writeEdaCode(tmpRhfl);

            // (3)RData Replication file
            String wrkspFileName = resultInfo.get("wrkspFileName");
            dbgLog.info("wrkspFileName=" + wrkspFileName);

            File RwrkspFileName = new File(wrkspFileName);
            if (RwrkspFileName.exists()) {
                dbgLog.info("RwrkspFileName:length=" + RwrkspFileName.length());

                zipFileList.add(RwrkspFileName);

            } else {
                dbgLog.info("RwrkspFileName does not exist");
                //msgEdaButton.setValue("* The workspace file is not available");
                //msgEdaButton.setVisible(true);
                dbgLog.warning("edaAction(): R workspace file was not transferred");
                //getVDCRequestBean().setSelectedTab("tabEda");

                //return "failure";
            }
            deleteTempFileList.add(RwrkspFileName);

            //                // vdc_startup.R file
            //                String vdc_startupFileName = resultInfo.get("vdc_startupFileName");
            //                dbgLog.fine("vdc_startupFileName="+vdc_startupFileName);
            //                File vdcstrtFileName = new File(vdc_startupFileName);
            //                if (vdcstrtFileName.exists()){
            //                    dbgLog.fine("vdcstrtFileName:length="+vdcstrtFileName.length());
            //                    zipFileList.add(vdcstrtFileName);
            //                } else {
            //                    dbgLog.fine("vdcstrtFileName does not exist");
            //                    //msgEdaButton.setValue("* vdc_startup.R is not available");
            //                    //msgEdaButton.setVisible(true);
            //                    dbgLog.warning("edaAction(): vdc_startup.R was not transferred");
            //                    //getVDCRequestBean().setSelectedTab("tabEda");
            //
            //                    //return "failure";
            //                }
            //                deleteTempFileList.add(vdcstrtFileName);
            // add replication readme file
            // (4) readme file
            // zipFileList.add(REP_README_FILE);
            String readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt";
            File readMeFile = new File(TEMP_DIR, readMeFileName);

            DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo);
            rw.writeREADMEfile(readMeFile);
            //zipFileList.add(REP_README_FILE);
            zipFileList.add(readMeFile);
            deleteTempFileList.add(readMeFile);

            // (5) css file
            zipFileList.add(DVN_R2HTML_CSS_FILE);
            // (6) dvn_R_helper
            zipFileList.add(DVN_R_HELPER_FILE);
            // zip the following files as a replication-pack
            //
            // local     local        local      remote
            // citation, tab-file,   R history,  wrksp

            for (File f : zipFileList) {
                dbgLog.fine("path=" + f.getAbsolutePath() + "\tname=" + f.getName());
            }

            // zipping all required files
            try {
                String zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip";
                File zipFile = new File(TEMP_DIR, zipFilePrefix);

                //res.setContentType("application/zip");
                String zfname = zipFile.getAbsolutePath();
                //res.setHeader("content-disposition", "attachment; filename=" + zfname);

                OutputStream zfout = new FileOutputStream(zipFile);
                //zipFiles(res.getOutputStream(), zipFileList);
                zipFiles(zfout, zipFileList);
                deleteTempFileList.add(zipFile);
                if (zipFile.exists()) {
                    Long zipFileSize = zipFile.length();
                    dbgLog.info("zip file:length=" + zipFileSize);
                    dbgLog.info("zip file:name=" + zipFile.getAbsolutePath());
                    if (zipFileSize > 0) {
                        resultInfo.put("replicationZipFile", zfname);
                        resultInfo.put("replicationZipFileName", zipFile.getName());
                    } else {
                        dbgLog.info("zip file is empty");
                    }
                } else {
                    dbgLog.info("zip file was not saved");
                }

                resultInfo.remove("RCommandHistory");

                // put resultInfo into the session object

                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("resultInfo",
                        resultInfo);

                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);

                dbgLog.info("***** within edaAction(): succcessfully ends here *****");

                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix();
                //return "success";

            } catch (IOException e) {
                // file-access problem, etc.
                e.printStackTrace();
                dbgLog.info("zipping IO exception");
                msgEdaButton.setValue("* an IO problem occurred during zipping replication files");
                msgEdaButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to an zipping IO problem ");
                //getVDCRequestBean().setSelectedTab("tabEda");
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix();
                //return "success";
            }
            // end of zipping step

        } catch (IOException e) {
            // io errors caught during writing files
            e.printStackTrace();

            msgEdaButton.setValue("* an IO problem occurred");
            msgEdaButton.setVisible(true);
            dbgLog.warning("exiting edaAction() due to an IO problem ");
            getVDCRequestBean().setSelectedTab("tabEda");

            return "";
        }

        // end of CheckParameters: OK case
    } else {
        // parameters are not complete: show error message;
        msgEdaButton.setValue("* Select at least one option");
        msgEdaButton.setVisible(true);
        dbgLog.warning("exiting edaAction(): selection is incomplete");
        getVDCRequestBean().setSelectedTab("tabEda");

        return "";
    }

}

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public String dwnldAction() {
    dbgLog.fine("***** within dwnldAction() *****");

    resetMsgDwnldButton();//from   ww w  .  j  ava2s  .c  o  m

    if (checkDwnldParameters()) {

        FacesContext cntxt = FacesContext.getCurrentInstance();

        HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse();

        HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest();

        StudyFile sf = dataTable.getStudyFile();

        Long noRecords = dataTable.getRecordsPerCase();

        String dsbUrl = getDsbUrl();
        dbgLog.fine("dsbUrl=" + dsbUrl);

        String serverPrefix = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();

        dbgLog.fine("serverPrefix" + serverPrefix);

        Map<String, List<String>> mpl = new HashMap<String, List<String>>();

        // File inFile = new File(sf.getFileSystemLocation());
        // File origFile = new File(inFile.getParent(), "_" + sf.getFileSystemName());

        String formatType = (String) dwnldFileTypeSet.getValue();
        dbgLog.fine("file type from the binding=" + formatType);
        if (formatType == null) {
            formatType = dwnldFileTypeSelected;
            dbgLog.fine("file type from the value=" + dwnldFileTypeSelected);
        }
        mpl.put("dtdwnld", Arrays.asList(formatType));

        dbgLog.fine("citation info to be sent:\n" + getCitation());

        mpl.put("studytitle", Arrays.asList(getStudyTitle()));
        dbgLog.fine("studyId=" + getStudyId().toString());
        mpl.put("studyno", Arrays.asList(getStudyId().toString()));
        mpl.put("studyURL", Arrays.asList(studyURL));

        mpl.put("", Arrays.asList(""));
        mpl.put("browserType", Arrays.asList(browserType));

        mpl.put("recodedVarIdSet", getRecodedVarIdSet());
        mpl.put("recodedVarNameSet", getRecodedVarNameSet());
        mpl.put("recodedVarLabelSet", getRecodedVarLabelSet());
        mpl.put("recodedVarTypeSet", getRecodedVariableType());
        mpl.put("recodedVarBaseTypeSet", getBaseVariableTypeForRecodedVariable());

        mpl.put("baseVarIdSet", getBaseVarIdSetFromRecodedVarIdSet());
        mpl.put("baseVarNameSet", getBaseVarNameSetFromRecodedVarIdSet());

        mpl.put("requestType", Arrays.asList("Download"));

        // Added by Matt Owen to find a way to sneak in Metadata that is lost between Rdata -> Tab 
        mpl.put("originalFile", Arrays.asList(getOriginalFileSystemLocation().getAbsolutePath()));

        // -----------------------------------------------------
        // Processing route, step by step:
        // 
        // Step 0. Locate the data file and its attributes

        String fileId = sf.getId().toString();

        String fileloc = sf.getFileSystemLocation();
        String tabflnm = sf.getFileName();
        boolean sbstOK = sf.isSubsettable();
        String flct = sf.getFileType();

        // Output debug statements
        dbgLog.info("location=" + fileloc);
        dbgLog.info("filename=" + tabflnm);
        dbgLog.info("subsettable=" + sbstOK);
        dbgLog.info("filetype=" + flct);
        dbgLog.info("studyUrl = " + studyURL);
        dbgLog.info("original file asbolute path = " + getOriginalFileSystemLocation().getAbsolutePath());

        // D
        DvnRJobRequest sro = null;

        List<File> zipFileList = new ArrayList();

        File tmpsbfl = null;

        if (sbstOK) {

            try {

                // this temp file will store the requested column(s):
                tmpsbfl = File.createTempFile("tempsubsetfile.", ".tab");
                deleteTempFileList.add(tmpsbfl);

                // to produce this file, we'll either open the stream
                // and run our local subsetting code on it, or request
                // the subsetting to be performed natively by the access
                // driver, if it supports the functionality:

                // check whether a source file is tab-delimited or not

                boolean fieldcut = true;
                if ((noRecords != null) && (noRecords >= 1)) {
                    fieldcut = false;
                }

                DataAccessRequest daReq = new DataAccessRequest();
                daReq.setParameter("noVarHeader", "1");

                DataAccessObject accessObject = DataAccess.createDataAccessObject(sf, daReq);

                if (accessObject.isSubsetSupported()) {
                    dbgLog.fine("Using NATIVE subset functionality of the repository.");
                    daReq.setParameter("vars", getVariableNamesForSubset());

                    accessObject.open();

                    InputStream inSubset = accessObject.getInputStream();
                    OutputStream outSubset = new BufferedOutputStream(
                            new FileOutputStream(tmpsbfl.getAbsolutePath()));

                    int bufsize = 8192;
                    byte[] subsetDataBuffer = new byte[bufsize];
                    while ((bufsize = inSubset.read(subsetDataBuffer)) != -1) {
                        outSubset.write(subsetDataBuffer, 0, bufsize);
                    }

                    inSubset.close();
                    outSubset.close();

                    // TODO: catch exceptions; reset the state of the page
                    // if anything went wrong. See the fixed-field section
                    // below for an example.

                } else {
                    accessObject.open();

                    if (fieldcut) {
                        // Cutting requested fields of data from a TAB-delimited stream:

                        Set<Integer> fields = getFieldNumbersForSubsetting();
                        dbgLog.fine("subsetting fields=" + fields);

                        // Create an instance of DvnJavaFieldCutter
                        FieldCutter fc = new DvnJavaFieldCutter();

                        // Executes the subsetting request
                        fc.subsetFile(accessObject.getInputStream(), tmpsbfl.getAbsolutePath(), fields,
                                dataTable.getCaseQuantity(), "\t");

                        // TODO: catch exceptions; reset the state of the page
                        // if anything went wrong. See the fixed-field section
                        // below for an example.

                    } else {
                        // Cutting requested columns of data from a fixed-field stream:

                        Map<Long, List<List<Integer>>> varMetaSet = getSubsettingMetaData(noRecords);
                        DvnNewJavaFieldCutter fc = new DvnNewJavaFieldCutter(varMetaSet);

                        try {
                            //fc.cutColumns(new File(cutOp1), noRecords.intValue(), 0, "\t", tmpsbfl.getAbsolutePath());
                            fc.cutColumns(accessObject.getInputStream(), noRecords.intValue(), 0, "\t",
                                    tmpsbfl.getAbsolutePath());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an IO problem");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        } catch (RuntimeException re) {
                            re.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an runtime error");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an runtime error");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        }

                    }
                }

                // Checks the resulting subset file:

                if (tmpsbfl.exists()) {
                    Long subsetFileSize = tmpsbfl.length();
                    dbgLog.fine("subset file:Length=" + subsetFileSize);
                    dbgLog.fine("subset file:name=" + tmpsbfl.getAbsolutePath());

                    if (subsetFileSize > 0) {
                        mpl.put("subsetFileName", Arrays.asList(tmpsbfl.getAbsolutePath()));
                        mpl.put("subsetDataFileName", Arrays.asList(tmpsbfl.getName()));
                    } else {
                        // subset file exists but it is empty

                        msgDwnldButton.setValue("* an subset file is empty");
                        msgDwnldButton.setVisible(true);
                        dbgLog.warning(
                                "exiting dwnldAction() due to a subsetting error:" + "a subset file is empty");
                        getVDCRequestBean().setSelectedTab("tabDwnld");
                        dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                        return "";

                    }
                } else {
                    // subset file was not created
                    msgDwnldButton.setValue("* a subset file was not created");
                    msgDwnldButton.setVisible(true);
                    dbgLog.warning("exiting dwnldAction() due to a subsetting error:"
                            + "a subset file was not created");
                    getVDCRequestBean().setSelectedTab("tabDwnld");
                    dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                    return "";

                }

                // If we've made it this far, we can increment the number of
                // downloads for the study file:

                VDC vdc = vdcService.getVDCFromRequest(req);
                GuestBookResponse guestbookResponse = (GuestBookResponse) getVDCSessionBean()
                        .getGuestbookResponseMap().get("guestBookResponse_" + sf.getStudy().getId());

                if (guestbookResponse == null) {
                    //need to set up dummy network response
                    guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(sf.getStudy(),
                            sf, getVDCSessionBean().getLoginBean());
                }
                guestbookResponse.setStudyVersion(sf.getStudy().getStudyVersionByNumber(versionNumber));
                String jsessionId = null;
                Cookie cookies[] = req.getCookies();

                for (int i = 0; i < cookies.length; i++) {
                    if ("JSESSIONID".equals(cookies[i].getName())) {
                        jsessionId = cookies[i].getValue();
                    }
                }

                if (jsessionId == null || "".equals(jsessionId)) {
                    String[] stringArray = getVDCSessionBean().toString().split("@");
                    jsessionId = stringArray[1];
                }

                guestbookResponse.setSessionId(jsessionId);

                String friendlyFormatName = "";
                String formatRequestedMimeType = "";

                if (formatType != null && !"".equals(formatType)) {
                    if (formatType.equals("D00")) {
                        formatRequestedMimeType = "text/tab-separated-values"; // tabular
                    } else if (formatType.equals("D01")) {
                        formatRequestedMimeType = "text/tab-separated-values"; // fixed-field
                    } else {
                        for (DataFileFormatType type : studyService.getDataFileFormatTypes()) {
                            if (formatType.equals(type.getValue())) {
                                formatRequestedMimeType = type.getMimeType();
                            }
                        }
                    }
                }

                if (formatRequestedMimeType == null || "".equals(formatRequestedMimeType)) {
                    formatRequestedMimeType = "application/x-unknown";
                }

                friendlyFormatName = FileUtil.getUserFriendlyTypeForMime(formatRequestedMimeType);
                guestbookResponse.setDownloadtype("Subsetting - " + friendlyFormatName);

                if (vdc != null) {
                    studyService.incrementNumberOfDownloads(sf.getId(), vdc.getId(),
                            (GuestBookResponse) guestbookResponse);
                } else {
                    studyService.incrementNumberOfDownloads(sf.getId(), (Long) null,
                            (GuestBookResponse) guestbookResponse);
                }

                // Step 3. Organizes parameters/metadata to be sent to the implemented
                // data-analysis-service class

                // skip the Rserve call completely (for plain tab file format, with no recoding)! -- L.A.
                if (!formatType.equals("D01") || (recodeSchema.size() > 0)) {

                    Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables();

                    // New (as of 3.6): support for ordered categorical variables 
                    // (ingested from R ordered factors). 
                    // Note that this is only being added here, i.e., to the 
                    // download-and-save part; if/when we make the analysis 
                    // and statistics utilize/handle these ordered categories 
                    // in some special way, we'll need to add the actual 
                    // ordered values to the SRO objects there as well. -- L.A. 

                    Map<String, List<String>> categoryOrders = getCategoryValueOrdersForAllRequestedVariables();

                    if (categoryOrders != null) {
                        sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema,
                                categoryOrders, null);
                    } else {
                        sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema);
                    }

                    /*
                     * Add the recoded -> base variable name map; (new as of v3.6;)
                     * TODO: (?) do the same for the other action requests. 
                     *          -- L.A.
                     */
                    sro.setRecodedToBaseVar(getRecodedVarToBaseVarName());

                    // dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE));

                    // Step 4. Creates an instance of the the implemented
                    // data-analysis-service class

                    DvnRDataAnalysisServiceImpl das = new DvnRDataAnalysisServiceImpl();

                    // Executes a download or data analysis request and
                    // stores the results in a Map <String, String>

                    resultInfo = das.execute(sro);

                    // Step 5. Check the exit status of the R process:

                    if (resultInfo.get("RexecError").equals("true")) {

                        msgDwnldButton.setValue("* The Request failed due to an R-runtime error");
                        msgDwnldButton.setVisible(true);
                        dbgLog.fine("exiting dwnldAction() due to an R-runtime error");
                        getVDCRequestBean().setSelectedTab("tabDwnld");
                        dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                        return "";
                    }
                }

                if (recodeSchema.size() > 0) {
                    resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation());
                } else {
                    resultInfo.put("subsettingCriteria", "variables: " + getVariableNamesForSubset());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();

                msgDwnldButton.setValue("* file URL is malformed");
                msgDwnldButton.setVisible(true);
                dbgLog.warning("exiting dwnldAction() due to a URL problem ");
                getVDCRequestBean().setSelectedTab("tabDwnld");

                return "";

            } catch (IOException e) {
                // this may occur if the dataverse is not released,
                // or if the file exists, but it is not accessible, etc.
                e.printStackTrace();

                msgDwnldButton.setValue("* an IO problem occurred");
                msgDwnldButton.setVisible(true);
                dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabDwnld");

                return "";
            }

            // end of subset-OK case
        } else {
            // not subsettable data file
            msgDwnldButton.setValue("* this data file is not subsettable file");
            msgDwnldButton.setVisible(true);
            dbgLog.warning("exiting dwnldAction(): the data file is not subsettable ");
            getVDCRequestBean().setSelectedTab("tabDwnld");
            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
            return "";

        } // end:subsetNotOKcase

        // final processing steps for all successful cases
        // add study-metadata to the resultInfo map

        if (formatType.equals("D01") && !(recodeSchema.size() > 0)) {
            resultInfo.put("wbDataFileName", tmpsbfl.getAbsolutePath());
            // Fields that would normally be populated by R:

            resultInfo.put("PID", "N/A");
            resultInfo.put("R_min_verion_no", "N/A");
            resultInfo.put("dsbHost", "N/A");
            Date now = new Date();
            resultInfo.put("RexecDate", now.toString());
        } else {
            resultInfo.put("R_min_verion_no", resultInfo.get("Rversion").substring(2));
        }

        resultInfo.put("offlineCitation", getCitation());
        resultInfo.put("studyTitle", getStudyTitle());
        resultInfo.put("studyNo", getStudyId().toString());
        resultInfo.put("dtId", dtId.toString());
        if (versionNumber != null) {
            resultInfo.put("versionNumber", versionNumber.toString());
        }
        resultInfo.put("studyURL", studyURL);
        resultInfo.put("dataverse_version_no", dvnVersionNumber);

        resultInfo.put("option", "subset");
        resultInfo.put("variableList", getVariableNamesForSubset());

        // calculate UNF (locally, on the application side):

        List<DataVariable> subsetVariableList = getDataVariableForRequest();

        String subsetUNFvalue = "[NOT CALCULATED]";

        String[] unfValues = new String[subsetVariableList.size()];

        for (int i = 0; i < subsetVariableList.size(); i++) {
            unfValues[i] = subsetVariableList.get(i).getUnf();
        }

        dbgLog.fine("unf set:\n" + Arrays.deepToString(unfValues));

        try {
            subsetUNFvalue = UNF5Util.calculateUNF(unfValues);

        } catch (NumberFormatException ex) {
            // if anything went wrong during the UNF calculation, it's not
            // a fatal condition; we'll just be displaying "not calculated"
            // instead of the UNF in the final README file.

            dbgLog.fine("error while trying to calculate subset UNF: Number Format Exception.");
            ex.printStackTrace();
        } catch (IOException ex) {
            dbgLog.fine("error while trying to calculate subset UNF: IO Exception.");
            ex.printStackTrace();
        }

        resultInfo.put("fileUNF", subsetUNFvalue);

        // writing necessary files:

        try {

            if (formatType.equals("D01") && !(recodeSchema.size() > 0)) {
                // (2) tab-delimited-format-only step:
                //
                // In the final zip file we package the subset file
                // and a replication README file (also contains citation). 
                // We also *used to* include the SAS, SPSS and R control
                // files created by R. We are not doing this anymore, but 
                // I left the code commented-out below. 
                //                  -- L.A. Jan. 2012
                //
                // We are also adding the variable header to the file here.

                /* SKIP CODE FILES -- L.A.
                String codeFileSas = "codeFile_sas_" + resultInfo.get("PID") + ".sas";
                File tmpCCsasfl = new File(TEMP_DIR, codeFileSas);
                        
                deleteTempFileList.add(tmpCCsasfl);
                zipFileList.add(tmpCCsasfl);
                        
                String codeFileSpss = "codeFile_spss_" + resultInfo.get("PID") + ".sps";
                File tmpCCspsfl = new File(TEMP_DIR, codeFileSpss);
                        
                deleteTempFileList.add(tmpCCspsfl);
                zipFileList.add(tmpCCspsfl);
                        
                String codeFileStata = "codeFile_stata_" + resultInfo.get("PID") + ".do";
                File tmpCCdofl  = new File(TEMP_DIR, codeFileStata);
                        
                deleteTempFileList.add(tmpCCdofl);
                zipFileList.add(tmpCCdofl);
                        
                StatisticalCodeFileWriter scfw = new StatisticalCodeFileWriter(sro);
                scfw.write(tmpCCsasfl, tmpCCspsfl, tmpCCdofl);
                 */

                // add the subset file:

                File tmpsbflnew = File.createTempFile("tempsubsetfile_new.", ".tab");
                deleteTempFileList.add(tmpsbflnew);

                InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl));
                OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew));

                String varHeaderLine = getVariableHeaderForSubset();
                // Add the variable header to the subset file:
                byte[] varHeaderBuffer = null;
                varHeaderBuffer = varHeaderLine.getBytes();
                outb.write(varHeaderBuffer);
                outb.flush();

                int bufsize;
                byte[] bffr = new byte[8192];
                while ((bufsize = inb.read(bffr)) != -1) {
                    outb.write(bffr, 0, bufsize);
                }
                inb.close();
                outb.close();

                dbgLog.fine("adding tab file: " + tmpsbflnew.getName());
                zipFileList.add(tmpsbflnew);

            } else {

                // (2)The format-converted subset data file
                String wbDataFileName = resultInfo.get("wbDataFileName");
                dbgLog.fine("wbDataFileName=" + wbDataFileName);

                File wbSubsetDataFile = new File(wbDataFileName);
                if (wbSubsetDataFile.exists()) {
                    dbgLog.fine("wbSubsetDataFile:length=" + wbSubsetDataFile.length());
                    deleteTempFileList.add(wbSubsetDataFile);
                    zipFileList.add(wbSubsetDataFile);
                } else {
                    // the data file was not created
                    dbgLog.fine("wbSubsetDataFile does not exist");

                    msgDwnldButton.setValue("* The requested data file is not available");
                    msgDwnldButton.setVisible(true);
                    dbgLog.warning("exiting dwnldAction(): data file was not transferred");
                    getVDCRequestBean().setSelectedTab("tabDwnld");
                    dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                    return "";
                }
            }

            // Create README file:

            String readMeFileName = null;

            if (resultInfo.get("PID") != null && !resultInfo.get("PID").equals("N/A")) {
                readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt";
            } else {
                readMeFileName = REP_README_FILE_PREFIX + fileId + ".txt";
            }

            File readMeFile = new File(TEMP_DIR, readMeFileName);

            DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo);
            rw.writeREADMEfile(readMeFile, true);

            zipFileList.add(readMeFile);
            deleteTempFileList.add(readMeFile);

            for (File f : zipFileList) {
                dbgLog.fine("file to zip: path=" + f.getAbsolutePath() + "\tname=" + f.getName());
            }

            // We can now zip all the required files"
            try {
                String zipFilePrefix = null;

                if (resultInfo.get("PID") != null && !resultInfo.get("PID").equals("N/A")) {
                    zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip";
                } else {
                    zipFilePrefix = "zipFile_" + fileId + ".zip";

                }
                File zipFile = new File(TEMP_DIR, zipFilePrefix);

                //deleteTempFileList.add(zipFile);
                String zfname = zipFile.getName();
                zipFileName = zfname;
                zipFiles(new FileOutputStream(zipFile), zipFileList);

                /*
                try {
                Thread.sleep(1000);
                } catch (Exception e) {
                        
                }
                 */

                zipResourceDynFileName = new ByteArrayResource(
                        toByteArray(new FileInputStream(zipFile.getAbsolutePath())));
                dbgLog.info("Subsetting: zipFileName=" + zipFileName);
                dbgLog.info("Subsetting: zipFile, absolute path: " + zipFile.getAbsolutePath());
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);

                // Hide 'Create' button, show 'Download' button:
                dwnldButton.setRendered(false);
                dwnloadSubsetButton.setRendered(true);
                dbgLog.info("***** within dwnldAction(): ends here *****");

                /*
                 * Navigation: 
                 *  - is it necessary to use "faces-redirect" navigation here? 
                 *    Or should we simply return "" as long as we want to stay 
                 *    on the subsetting page?
                if (versionNumber != null) {
                    return "/study/SubsettingPage?faces-redirect=true&dtId=" + dtId + "&versionNumber=" + versionNumber;
                }
                return "/study/SubsettingPage?faces-redirect=true&dtId=" + dtId;
                 */
                return "";

            } catch (IOException e) {
                // file-access problem, etc.
                e.printStackTrace();
                dbgLog.fine("download zipping IO exception");
                msgDwnldButton.setValue("* an IO problem occurred");
                msgDwnldButton.setVisible(true);
                dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabDwnld");
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                return "";
            }
            // end of zipping step

        } catch (IOException e) {
            e.printStackTrace();

            msgDwnldButton.setValue("* an IO problem occurred");
            msgDwnldButton.setVisible(true);
            dbgLog.warning("exiting dwnldAction() due to an IO problem ");
            getVDCRequestBean().setSelectedTab("tabDwnld");
            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
            return "";
        }

        // end: params are OK-case
    } else {
        // the selection is incomplete
        // show error message;
        pgDwnldErrMsg.setRendered(true);
        msgDwnldButton.setValue("* Error: Select a file format");
        msgDwnldButton.setVisible(true);
        dbgLog.warning("exiting dwnldAction() due to incomplete data ");
        getVDCRequestBean().setSelectedTab("tabDwnld");

        return "";
    } // end: checking params

}

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public String advStatAction() {
    //        dbgLog.fine("selected tab(advStat)="+getTabSet1().getSelected());
    // check the current model

    String mdlName = (String) dropDown1.getValue();
    dbgLog.fine("model name=" + mdlName);

    AdvancedStatGUIdata.Model modelSpec = getAnalysisApplicationBean().getSpecMap().get(mdlName);

    if (checkAdvStatParameters(mdlName)) {

        FacesContext cntxt = FacesContext.getCurrentInstance();

        HttpServletResponse res = (HttpServletResponse) cntxt.getExternalContext().getResponse();
        HttpServletRequest req = (HttpServletRequest) cntxt.getExternalContext().getRequest();

        dbgLog.fine("***** within advStatAction() *****");
        // common parts
        // data file
        StudyFile sf = dataTable.getStudyFile();
        Long noRecords = dataTable.getRecordsPerCase();

        String dsbUrl = getDsbUrl();
        dbgLog.fine("dsbUrl=" + dsbUrl);

        String serverPrefix = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();/* w  w w. java 2s . c om*/

        dbgLog.fine("serverPrefix=" + serverPrefix);
        //                /
        //                  "optnlst_a" => "A01|A02|A03", "analysis" => "A01 A02",
        //                  "varbl" => "v1.3 v1.10 v1.13 v1.22 v1.40", "charVarNoSet" =>
        //                  "v1.10|v1.719",
        //                 /

        // common parameters
        Map<String, List<String>> mpl = new HashMap<String, List<String>>();

        List<String> alst = new ArrayList<String>();
        List<String> aoplst = new ArrayList<String>();

        aoplst.add("A01|A02|A03");
        mpl.put("optnlst_a", aoplst);

        Map<String, List<String>> xtbro = new HashMap<String, List<String>>();

        // xtbro: modelName
        xtbro.put("modelName", Arrays.asList(mdlName));

        // outoput options

        List<String> outOptionList = new ArrayList<String>();

        mpl.put("modelName", Arrays.asList(mdlName));
        if (mdlName.equals("xtb")) {
            mpl.put("requestType", Arrays.asList("Xtab"));
        } else {
            mpl.put("requestType", Arrays.asList("Zelig"));
        }

        if (mdlName.equals("xtb")) {
            alst.add("A03");

            // output options
            // Object[] outOptn = (Object[]) checkboxGroupXtbOptions.getSelectedValue();
            Object[] outOptn = chkbxAdvStatOutputXtbOpt.getSelectedValues();
            List<String> tv = new ArrayList<String>();
            //tv.add("T");

            for (int j = 0; j < outOptn.length; j++) {
                dbgLog.fine("output option[" + j + "]=" + outOptn[j]);
                mpl.put((String) outOptn[j], Arrays.asList("T"));
                tv.add((String) outOptn[j]);
            }
            mpl.put("xtb_outputOptions", tv);

            // variables: 1st RBox
            if (advStatVarRBox1.size() >= 1) {
                dbgLog.fine("RB1:" + getDataVariableForRBox1());
                mpl.put("xtb_nmBxR1", getDataVariableForRBox1());
            }

            // variables: 2nd RBox
            if (advStatVarRBox2.size() >= 1) {
                dbgLog.fine("RB2:" + getDataVariableForRBox2());
                mpl.put("xtb_nmBxR2", getDataVariableForRBox2());
            }

            mpl.put("analysis", alst);

        } else {
            // Zelig cases

            dbgLog.fine("***** zelig param block *****");
            // non-xtb, i.e., zelig cases
            // check zlg value

            dbgLog.fine("model spec dump=" + modelSpec);
            dbgLog.fine("model spec mdlId=" + modelSpec.getMdlId());

            String zligPrefix = modelSpec.getMdlId();
            dbgLog.fine("model no=" + zligPrefix);

            // get the varId-list of each box
            // 1-RBox case
            if (advStatVarRBox1.size() >= 1) {
                dbgLog.fine("RB1:" + getDataVariableForRBox1());
                //mpl.put(zligPrefix + "_nmBxR1", getDataVariableForRBox1());
                mpl.put("nmBxR1", getDataVariableForRBox1());
            }

            // 2-RBox case
            if (advStatVarRBox2.size() >= 1) {
                dbgLog.fine("RB2:" + getDataVariableForRBox2());
                //mpl.put(zligPrefix + "_nmBxR2", getDataVariableForRBox2());
                mpl.put("nmBxR2", getDataVariableForRBox2());
            }

            // 3-RBox case
            if (advStatVarRBox3.size() >= 1) {
                dbgLog.fine("RB3:" + getDataVariableForRBox3());
                //mpl.put(zligPrefix + "_nmBxR3", getDataVariableForRBox3());
                mpl.put("nmBxR3", getDataVariableForRBox3());
            }

            // model name
            //mpl.put("zlg", getZlg(zligPrefix, mdlName));

            // model type
            //String sfn = modelSpec.getSpecialFn();
            //mpl.put("mdlType_" + mdlName, getMdlType(mdlName, sfn));

            // model title
            //String ttl = modelSpec.getTitle();
            //dbgLog.fine("model title=" + ttl);
            //mpl.put("mdlTitle_" + mdlName, Arrays.asList(ttl));
            //mpl.put("mdlTitle", Arrays.asList(ttl));

            // nrBoxes
            int noRboxes = modelSpec.getNoRboxes();
            dbgLog.fine("noRboxes=" + noRboxes);

            //mpl.put("noBoxes_" + mdlName, Arrays.asList(Integer.toString(noRboxes)));
            mpl.put("noBoxes", Arrays.asList(Integer.toString(noRboxes)));

            // binary
            String mdlCategory = modelSpec.getCategory();
            String outcomeType = modelSpec.getVarBox().get(0).getVarType();

            dbgLog.fine("model category=" + mdlCategory);

            if (mdlCategory.equals("Models for Dichotomous Dependent Variables")) {
                mpl.put("mdlDepVarType", Arrays.asList("binary"));
            }
            if (outcomeType.equals("binary")) {
                mpl.put("isOutcomeBinary", Arrays.asList("T"));
            } else {
                mpl.put("isOutcomeBinary", Arrays.asList("F"));
            }
            // output options
            //                    //
            //                     // zlg_017_Summary zlg_017_Plots zlg_017_BinOutput
            //                     //
            //Object[] outOptn = (Object[]) checkboxGroup2DefaultOptions.getSelectedValue();
            Object[] outOptn = chkbxAdvStatOutputOpt.getSelectedValues();
            List<String> tv = new ArrayList<String>();

            for (int j = 0; j < outOptn.length; j++) {
                //String outputOptnkey = zligPrefix + "_"+ (String) outOptn[j];
                String outputOptnkey = (String) outOptn[j];
                dbgLog.fine("zelig: output option[" + j + "]=" + outputOptnkey);
                mpl.put(outputOptnkey, Arrays.asList("T"));
                tv.add((String) outOptn[j]);
            }
            mpl.put("zelig_outputOptions", tv);

            // analysis options
            //                    
            //                      zlg_017_Sim zlg_017_setx zlg_017_setx_var
            //                      zlg_017_setx_val_1 zlg_017_setx_val_2
            //                      
            //                      zlg_017_naMethod
            //                     
            //
            dbgLog.fine("simulationPanel is selected=" + simulationPanel.isSelected());
            if (simulationPanel.isSelected()) {
                dbgLog.fine("radioSimTypeChoiceSelected=" + radioSimTypeChoiceSelected);
                //mpl.put(zligPrefix + "_Sim", Arrays.asList("T"));
                mpl.put("Sim", Arrays.asList("T"));

                //Object simOptn = radioButtonGroup1DefaultOptions.getSelectedValue();
                dbgLog.fine("radioSimTypeChoice(value)=" + radioSimTypeChoice.getValue());
                dbgLog.fine("radioSimTypeChoiceSelected=" + radioSimTypeChoiceSelected);
                // simOptn = 0 or 1
                //mpl.put(zligPrefix + "_setx", Arrays.asList((String) simOptn));
                //                        mpl.put("setx", Arrays.asList((String) simOptn));
                //                        mpl.put("setxType", Arrays.asList((String) simOptn));
                mpl.put("setx", Arrays.asList(radioSimTypeChoiceSelected));
                mpl.put("setxType", Arrays.asList(radioSimTypeChoiceSelected));
                if (radioSimTypeChoiceSelected.equals("1")) {
                    Object v1 = dropDown2.getValue();
                    Object v2 = dropDown3.getValue();
                    Object vl1 = textField10.getValue();
                    Object vl2 = textField8.getValue();
                    dbgLog.fine("v1=" + v1);
                    dbgLog.fine("v2=" + v2);
                    dbgLog.fine("vl1=" + vl1);
                    dbgLog.fine("vl2=" + vl2);

                    List<String> setxVars = new ArrayList<String>();

                    if (v1 != null) {
                        setxVars.add((String) v1);

                    }
                    if (v2 != null) {
                        setxVars.add((String) v2);
                    }
                    //mpl.put(zligPrefix + "_setx_var", setxVars);
                    mpl.put("setx_var", setxVars);

                    if (vl1 != null) {
                        //mpl.put(zligPrefix + "_setx_val_1", Arrays.asList((String) vl1));
                        mpl.put("setx_val_1", Arrays.asList((String) vl1));
                    }
                    if (vl2 != null) {
                        //mpl.put(zligPrefix + "_setx_val_2", Arrays.asList((String) vl2));
                        mpl.put("setx_val_2", Arrays.asList((String) vl2));
                    }

                    List<String> setxVar1 = new ArrayList<String>();

                    if (v1 != null) {
                        setxVar1.add("v" + v1);
                        if (vl1 != null) {
                            setxVar1.add((String) vl1);
                        } else {
                            setxVar1.add("");
                        }
                        mpl.put("setx_var1", setxVar1);
                    }

                    if (v2 != null) {
                        List<String> setxVar2 = new ArrayList<String>();

                        setxVar2.add("v" + v2);
                        if (vl2 != null) {
                            setxVar2.add((String) vl2);
                        } else {
                            setxVar2.add("");
                        }
                        mpl.put("setx_var2", setxVar2);
                    }

                }
            } else {
                mpl.put("Sim", Arrays.asList("F"));
            }

        }

        dbgLog.fine("contents(mpl so far):" + mpl);

        // if there is a user-defined (recoded) variables
        /*
        if (recodedVarSet.size() > 0) {
            mpl.putAll(getRecodedVarParameters());
        }
        */
        //                dbgLog.fine("citation info to be sent:\n" + citation);
        //                mpl.put("OfflineCitation", Arrays.asList(citation));
        //                mpl.put("appSERVER", Arrays.asList(req.getServerName() +
        //                    ":"+ req.getServerPort() + req.getContextPath()));

        mpl.put("studytitle", Arrays.asList(getStudyTitle()));
        dbgLog.fine("alt studyId=" + getStudyId().toString());
        mpl.put("studyno", Arrays.asList(getStudyId().toString()));
        mpl.put("studyURL", Arrays.asList(studyURL));
        mpl.put("browserType", Arrays.asList(browserType));

        mpl.put("recodedVarIdSet", getRecodedVarIdSet());
        mpl.put("recodedVarNameSet", getRecodedVarNameSet());
        mpl.put("recodedVarLabelSet", getRecodedVarLabelSet());
        mpl.put("recodedVarTypeSet", getRecodedVariableType());
        mpl.put("recodedVarBaseTypeSet", getBaseVariableTypeForRecodedVariable());

        mpl.put("baseVarIdSet", getBaseVarIdSetFromRecodedVarIdSet());
        mpl.put("baseVarNameSet", getBaseVarNameSetFromRecodedVarIdSet());

        // -----------------------------------------------------
        // New processing route
        // 
        // Step 0. Locate the data file and its attributes

        String fileId = sf.getId().toString();
        //VDC vdc = vdcService.getVDCFromRequest(req);

        String fileloc = sf.getFileSystemLocation();
        String tabflnm = sf.getFileName();
        boolean sbstOK = sf.isSubsettable();
        String flct = sf.getFileType();

        dbgLog.fine("location=" + fileloc);
        dbgLog.fine("filename=" + tabflnm);
        dbgLog.fine("subsettable=" + sbstOK);
        dbgLog.fine("filetype=" + flct);

        DvnRJobRequest sro = null;

        List<File> zipFileList = new ArrayList();

        // the data file for downloading/statistical analyses must be subset-ready
        // local (relative to the application) file case 
        // note: a typical remote case is: US Census Bureau
        File tmpsbfl = null;
        if (sbstOK) {

            try {
                // this temp file will store the requested columns:
                tmpsbfl = File.createTempFile("tempsubsetfile.", ".tab");
                deleteTempFileList.add(tmpsbfl);

                // to produce this file, we'll either open the stream
                // and run our local subsetting code on it, or request
                // the subsetting to be performed natively by the access
                // driver, if it supports the functionality:

                // check whether a source file is tab-delimited or not

                boolean fieldcut = true;
                if ((noRecords != null) && (noRecords >= 1)) {
                    fieldcut = false;
                }

                DataAccessRequest daReq = new DataAccessRequest();
                daReq.setParameter("noVarHeader", "1");

                DataAccessObject accessObject = DataAccess.createDataAccessObject(sf, daReq);

                if (accessObject.isSubsetSupported()) {
                    dbgLog.fine("Using NATIVE subset functionality of the repository.");
                    daReq.setParameter("vars", getVariableNamesForSubset());

                    accessObject.open();

                    InputStream inSubset = accessObject.getInputStream();
                    OutputStream outSubset = new BufferedOutputStream(
                            new FileOutputStream(tmpsbfl.getAbsolutePath()));

                    int bufsize = 8192;
                    byte[] subsetDataBuffer = new byte[bufsize];
                    while ((bufsize = inSubset.read(subsetDataBuffer)) != -1) {
                        outSubset.write(subsetDataBuffer, 0, bufsize);
                    }

                    inSubset.close();
                    outSubset.close();

                    // TODO: catch exceptions; reset the state of the page
                    // if anything went wrong. See the fixed-field section
                    // below for an example.

                } else {
                    accessObject.open();

                    if (fieldcut) {
                        // Cutting requested fields of data from a TAB-delimited stream:

                        Set<Integer> fields = getFieldNumbersForSubsetting();
                        dbgLog.fine("subsetting fields=" + fields);

                        // Create an instance of DvnJavaFieldCutter
                        FieldCutter fc = new DvnJavaFieldCutter();

                        // Executes the subsetting request
                        fc.subsetFile(accessObject.getInputStream(), tmpsbfl.getAbsolutePath(), fields,
                                dataTable.getCaseQuantity(), "\t");

                        // TODO: catch exceptions; reset the state of the page
                        // if anything went wrong. See the fixed-field section
                        // below for an example.

                    } else {
                        // Cutting requested columns of data from a fixed-field stream:

                        Map<Long, List<List<Integer>>> varMetaSet = getSubsettingMetaData(noRecords);
                        DvnNewJavaFieldCutter fc = new DvnNewJavaFieldCutter(varMetaSet);

                        try {
                            //fc.cutColumns(new File(cutOp1), noRecords.intValue(), 0, "\t", tmpsbfl.getAbsolutePath());
                            fc.cutColumns(accessObject.getInputStream(), noRecords.intValue(), 0, "\t",
                                    tmpsbfl.getAbsolutePath());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an IO problem");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an IO problem ");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return "";

                        } catch (RuntimeException re) {
                            re.printStackTrace();

                            msgDwnldButton.setValue("* could not generate subset due to an runtime error");
                            msgDwnldButton.setVisible(true);
                            dbgLog.warning("exiting dwnldAction() due to an runtime error");
                            getVDCRequestBean().setSelectedTab("tabDwnld");
                            dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                            return ""; //"failure";

                        }

                    }
                }

                // Checks the resulting subset file 
                if (tmpsbfl.exists()) {
                    Long subsetFileSize = tmpsbfl.length();
                    dbgLog.fine("subsettFile:Length=" + subsetFileSize);
                    dbgLog.fine("tmpsb file name=" + tmpsbfl.getAbsolutePath());

                    if (subsetFileSize > 0) {
                        mpl.put("subsetFileName", Arrays.asList(tmpsbfl.getAbsolutePath()));
                        mpl.put("subsetDataFileName", Arrays.asList(tmpsbfl.getName()));
                    } else {
                        // subset file exists but it is empty

                        msgAdvStatButton.setValue("* an subset file is empty");
                        msgAdvStatButton.setVisible(true);
                        dbgLog.warning("exiting advStatAction() due to a subsetting error:"
                                + "a subset file is empty");
                        getVDCRequestBean().setSelectedTab("tabAdvStat");

                        return ""; //"failure";

                    }
                } else {
                    // subset file was not created
                    msgAdvStatButton.setValue("* a subset file was not created");
                    msgAdvStatButton.setVisible(true);
                    dbgLog.warning("exiting advStatAction() due to a subsetting error:"
                            + "a subset file was not created");
                    getVDCRequestBean().setSelectedTab("tabAdvStat");

                    return ""; //"failure";

                }

                // Step 3. Organizes parameters/metadata to be sent to the implemented
                // data-analysis-service class

                //Map<String, Map<String, String>> vls = getValueTableForRequestedVariables(getDataVariableForRequest());
                Map<String, Map<String, String>> vls = getValueTablesForAllRequestedVariables();

                sro = new DvnRJobRequest(getDataVariableForRequest(), mpl, vls, recodeSchema, modelSpec);

                //dbgLog.fine("Prepared sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE));

                // Step 4. Creates an instance of the the implemented
                // data-analysis-service class 

                DvnRDataAnalysisServiceImpl das = new DvnRDataAnalysisServiceImpl();

                // Executes a request of downloading or data analysis and 
                // capture result info as a Map <String, String>

                resultInfo = das.execute(sro);

                // Step 5. Checks the DSB-exit-status code
                if (resultInfo.get("RexecError").equals("true")) {
                    //msgAdvStatButton.setValue("* The Request failed due to an R-runtime error");
                    msgAdvStatButton.setValue("* The Request failed due to an R-runtime error");
                    msgAdvStatButton.setVisible(true);
                    dbgLog.fine("exiting advStatAction() due to an R-runtime error");
                    getVDCRequestBean().setSelectedTab("tabAdvStat");

                    return ""; //"failure";
                } else {
                    if (recodeSchema.size() > 0) {
                        resultInfo.put("subsettingCriteria", sro.getSubsetConditionsForCitation());
                    } else {
                        resultInfo.put("subsettingCriteria", "");
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                // pass the error message to the resultPage
                // resultInfo.put();
                msgAdvStatButton.setValue("* file URL is malformed");
                msgAdvStatButton.setVisible(true);
                dbgLog.warning("exiting advStatAction() due to a URL problem ");
                getVDCRequestBean().setSelectedTab("tabAdvStat");

                return ""; //"failure";

            } catch (IOException e) {
                // this may occur if the dataverse is not released
                // the file exists, but it is not accessible 
                e.printStackTrace();

                msgAdvStatButton.setValue("* an IO problem occurred");
                msgAdvStatButton.setVisible(true);
                dbgLog.warning("exiting advStatAction() due to an IO problem ");
                getVDCRequestBean().setSelectedTab("tabAdvStat");

                return ""; //"failure";

            }
            // end of the subset-OK case
        } else {
            // not subsettable data file
            msgAdvStatButton.setValue("* this data file is not subsettable file");
            msgAdvStatButton.setVisible(true);
            dbgLog.warning("exiting advStatAction(): the data file is not subsettable ");
            getVDCRequestBean().setSelectedTab("tabAdvStat");

            return ""; //"failure";

        } // end:subsetNotOKcase

        // final processing steps for all successful cases

        resultInfo.put("offlineCitation", getCitation());
        resultInfo.put("studyTitle", getStudyTitle());
        resultInfo.put("studyNo", getStudyId().toString());
        resultInfo.put("dtId", dtId.toString());
        if (versionNumber != null) {
            resultInfo.put("versionNumber", versionNumber.toString());
        }
        resultInfo.put("studyURL", studyURL);
        resultInfo.put("R_min_verion_no", resultInfo.get("Rversion").substring(2));
        resultInfo.put("dataverse_version_no", dvnVersionNumber);

        dbgLog.fine("RwrkspFileName=" + resultInfo.get("wrkspFileName"));

        // writing necessary files
        try {

            // rename the subsetting file
            File tmpsbflnew = File.createTempFile(SUBSET_FILENAME_PREFIX + resultInfo.get("PID") + ".", ".tab");
            deleteTempFileList.add(tmpsbflnew);
            InputStream inb = new BufferedInputStream(new FileInputStream(tmpsbfl));
            OutputStream outb = new BufferedOutputStream(new FileOutputStream(tmpsbflnew));

            int bufsize;
            byte[] bffr = new byte[8192];
            while ((bufsize = inb.read(bffr)) != -1) {
                outb.write(bffr, 0, bufsize);
            }
            inb.close();
            outb.close();

            String rhistNew = StringUtils.replace(resultInfo.get("RCommandHistory"), tmpsbfl.getName(),
                    tmpsbflnew.getName());

            //zipFileList.add(tmpsbflnew);

            // (1) write a citation file 
            //                String citationFilePrefix = "citationFile_"+ resultInfo.get("PID") + "_";
            //                File tmpcfl = File.createTempFile(citationFilePrefix, ".txt");
            //
            //                zipFileList.add(tmpcfl);
            //                deleteTempFileList.add(tmpcfl);
            //
            //                DvnCitationFileWriter dcfw = new DvnCitationFileWriter(resultInfo);
            //
            //                String fmpcflFullname = tmpcfl.getAbsolutePath();
            //                String fmpcflname = tmpcfl.getName();
            //                dcfw.write(tmpcfl);

            // (2) R command file
            String rhistoryFilePrefix = R_COMMAND_FILE_PREFIX + resultInfo.get("PID") + ".R";
            File tmpRhfl = new File(TEMP_DIR, rhistoryFilePrefix);

            zipFileList.add(tmpRhfl);
            deleteTempFileList.add(tmpRhfl);
            resultInfo.put("dvn_R_helper_file", "dvn_helper.R");
            DvnReplicationCodeFileWriter rcfw = new DvnReplicationCodeFileWriter(resultInfo);
            if (mdlName.equals("xtb")) {
                rcfw.writeXtabCode(tmpRhfl);
            } else {
                rcfw.writeZeligCode(tmpRhfl);
            }

            // (3) RData Replication file
            String wrkspFileName = resultInfo.get("wrkspFileName");
            dbgLog.fine("wrkspFileName=" + wrkspFileName);

            File RwrkspFileName = new File(wrkspFileName);
            if (RwrkspFileName.exists()) {
                dbgLog.fine("RwrkspFileName:length=" + RwrkspFileName.length());

                zipFileList.add(RwrkspFileName);

            } else {
                dbgLog.fine("RwrkspFileName does not exist");
                //msgAdvStatButton.setValue("* The workspace file is not available");
                //msgAdvStatButton.setVisible(true);
                dbgLog.warning("advStatAction(): R workspace file was not transferred");
                //getVDCRequestBean().setSelectedTab("tabAdvStat");

                //return "failure";
            }
            deleteTempFileList.add(RwrkspFileName);

            // vdc_startup.R file
            //                String vdc_startupFileName = resultInfo.get("vdc_startupFileName");
            //                dbgLog.fine("vdc_startupFileName="+vdc_startupFileName);
            //                File vdcstrtFileName = new File(vdc_startupFileName);
            //                if (vdcstrtFileName.exists()){
            //                    dbgLog.fine("vdcstrtFileName:length="+vdcstrtFileName.length());
            //                    zipFileList.add(vdcstrtFileName);
            //                } else {
            //                    dbgLog.fine("vdcstrtFileName does not exist");
            //                    //msgAdvStatButton.setValue("* vdc_startup.R is not available");
            //                    //msgAdvStatButton.setVisible(true);
            //                    dbgLog.warning("advStatAction(): vdc_startup.R was not transferred");
            //                    //getVDCRequestBean().setSelectedTab("tabAdvStat");
            //
            //                    //return "failure";
            //                }
            //                deleteTempFileList.add(vdcstrtFileName);
            // (4) add replication readme file
            String readMeFileName = REP_README_FILE_PREFIX + resultInfo.get("PID") + ".txt";
            File readMeFile = new File(TEMP_DIR, readMeFileName);

            DvnReplicationREADMEFileWriter rw = new DvnReplicationREADMEFileWriter(resultInfo);
            rw.writeREADMEfile(readMeFile);
            //zipFileList.add(REP_README_FILE);
            zipFileList.add(readMeFile);
            deleteTempFileList.add(readMeFile);
            // (5) helper
            zipFileList.add(DVN_R_HELPER_FILE);
            if (mdlName.equals("xtb")) {
                // (6) css file
                zipFileList.add(DVN_R2HTML_CSS_FILE);

            }
            // zip the following files as a replication-pack
            //
            // local     local        local      remote
            // citation, tab-file,   R history,  wrksp

            for (File f : zipFileList) {
                dbgLog.fine("path=" + f.getAbsolutePath() + "\tname=" + f.getName());
            }

            // zipping all required files
            try {
                String zipFilePrefix = "zipFile_" + resultInfo.get("PID") + ".zip";
                File zipFile = new File(TEMP_DIR, zipFilePrefix);

                deleteTempFileList.add(zipFile);
                //res.setContentType("application/zip");
                String zfname = zipFile.getAbsolutePath();
                //res.setHeader("content-disposition", "attachment; filename=" + zfname);

                OutputStream zfout = new FileOutputStream(zipFile);
                //zipFiles(res.getOutputStream(), zipFileList);
                zipFiles(zfout, zipFileList);

                if (zipFile.exists()) {
                    Long zipFileSize = zipFile.length();
                    dbgLog.fine("zip file:length=" + zipFileSize);
                    dbgLog.fine("zip file:name=" + zipFile.getAbsolutePath());
                    if (zipFileSize > 0) {
                        resultInfo.put("replicationZipFile", zfname);
                        resultInfo.put("replicationZipFileName", zipFile.getName());

                    } else {
                        dbgLog.fine("zip file is empty");
                    }
                } else {
                    dbgLog.fine("zip file was not saved");
                }

                // put resultInfo into the session object
                resultInfo.remove("RCommandHistory");
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("resultInfo",
                        resultInfo);

                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);

                dbgLog.fine("***** within advStatAction(): succcessfully ends here *****");

                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix(); //"success";

            } catch (IOException e) {
                // file-access problem, etc.
                e.printStackTrace();
                dbgLog.fine("zipping IO exception");
                msgAdvStatButton.setValue("* an IO problem occurred during zipping replication files");
                msgAdvStatButton.setVisible(true);
                dbgLog.warning("exiting edaAction() due to an zipping IO problem ");
                //getVDCRequestBean().setSelectedTab("tabAdvStat");
                dvnDSBTimerService.createTimer(deleteTempFileList, TEMP_FILE_LIFETIME);
                return "/subsetting/AnalysisResultsPage?faces-redirect=true" + getContextSuffix(); //"success";
            }
            // end of zipping step

        } catch (IOException e) {
            // io errors caught during writing files
            e.printStackTrace();

            msgAdvStatButton.setValue("* an IO problem occurred");
            msgAdvStatButton.setVisible(true);
            dbgLog.warning("exiting edaAction() due to an IO problem ");
            getVDCRequestBean().setSelectedTab("tabAdvStat");

            return ""; //"failure";
        }

        // end of CheckParameters: OK case
    } else {
        // parameters are not complete: show error message;

        msgAdvStatButton.setValue("* Selection is incomplete");
        msgAdvStatButton.setVisible(true);
        dbgLog.fine("exiting advStatAction(): selection is incomplete");
        getVDCRequestBean().setSelectedTab("tabAdvStat");

        return ""; //"failure";
    }

}

From source file:com.emc.plants.web.servlets.ShoppingServlet.java

/**
 * Main service method for ShoppingServlet
 *
 * @param req Object that encapsulates the request to the servlet
 * @param resp Object that encapsulates the response from the servlet
 *//*from   w w w.  j  a  v a  2  s.  com*/
public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = null;
    action = req.getParameter(Util.ATTR_ACTION);
    Util.debug("action=" + action);
    if (action.equals(ACTION_SHOPPING)) {
        String category = (String) req.getParameter("category");
        HttpSession session = req.getSession(true);
        // Get session category if none on request, such as
        // 'Continue Shopping' from the Shopping Cart jsp.
        if ((category == null) || (category.equals("null"))) {
            category = (String) session.getAttribute(Util.ATTR_CATEGORY);
        }
        // If categoyr still null, default to first category.
        if ((category == null) || (category.equals("null"))) {
            category = "0";
        }
        session.setAttribute(Util.ATTR_CATEGORY, category);
        // Get the shopping items from the catalog.
        Collection c = catalog.getItemsByCategory(Integer.parseInt(category));
        ArrayList items = new ArrayList(c);
        for (int i = 0; i < items.size();) {
            if (((Inventory) items.get(i)).isPublic())
                i++;
            else
                items.remove(i);
        }
        req.setAttribute(Util.ATTR_INVITEMS, items);
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_SHOPPING);
    } else if (action.equals(ACTION_PRODUCTDETAIL)) {
        String invID = (String) req.getParameter("itemID");
        req.setAttribute(Util.ATTR_INVITEM, catalog.getItemInventory(invID));
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_PRODUCT);
    } else if (action.equals(ACTION_GOTOCART)) {
        HttpSession session = req.getSession(true);
        // Get shopping cart.
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        if (shoppingCart != null) {
            // Make sure ShopingCart reference has not timed out.
            try {
                shoppingCart.getItems();
            }
            // TODO: what exception would be thrown?
            catch (RuntimeException e) {
                Util.debug("gotocart: shopping cart ref must have timed out");
                ShoppingCartContents cartContents = (ShoppingCartContents) session
                        .getAttribute(Util.ATTR_CART_CONTENTS);
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                session.setAttribute(Util.ATTR_CART, shoppingCart);
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_ADDTOCART)) {
        ShoppingCart shoppingCart = null;
        // Get shopping cart.
        HttpSession session = req.getSession(true);
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        if (shoppingCart == null) {
            Util.debug("shopping cart is NULL, must create it");
            shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
            System.out.println(
                    "Items:: " + shoppingCart.getItems() + " Size :: " + shoppingCart.getItems().size());
            shoppingCart.setItems(new ArrayList<ShoppingCartItem>());
        } else {
            // Make sure ShopingCart reference has not timed out.
            try {
                Util.debug("shopping cart is not null, check items, size=" + shoppingCart.getItems().size());
                shoppingCart.getItems();
            }
            // TODO: what exception would be thrown?
            catch (RuntimeException e) {
                // ShoppingCart timed out, so create a new one.
                Util.debug("addtocart: shopping cart ref must have timed out, create a new one");
                ShoppingCartContents cartContents = (ShoppingCartContents) session
                        .getAttribute(Util.ATTR_CART_CONTENTS);
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                if (cartContents != null) {
                    shoppingCart.setCartContents(cartContents);
                }
            }
        }
        // Add item to cart.
        if (shoppingCart != null) {
            String invID = req.getParameter("itemID");

            // Gets detached instance
            Inventory inv = catalog.getItemInventory(invID);
            ShoppingCartItem si = new ShoppingCartItem(inv);
            si.setQuantity(Integer.parseInt(req.getParameter("qty").trim()));
            shoppingCart.addItem(si);
            session.setAttribute(Util.ATTR_CART, shoppingCart);
            session.setAttribute(Util.ATTR_CART_CONTENTS, shoppingCart.getCartContents());
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_UPDATEQUANTITY)) {
        // Get shopping cart.
        HttpSession session = req.getSession(true);
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("updatequantity: shopping cart ref must have timed out, create a new one");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");

            if (cartContents != null) {
                shoppingCart.setCartContents(cartContents);
            }
        }
        // Update item quantity in cart.
        if (shoppingCart != null) {
            try {
                int cnt = 0;
                Collection c = shoppingCart.getItems();
                ArrayList items;

                if (c instanceof ArrayList)
                    items = (ArrayList) c;
                else
                    items = new ArrayList(c);
                ShoppingCartItem si;
                String parm, parmval;
                // Check all quantity values from cart form.
                for (int parmcnt = 0;; parmcnt++) {
                    parm = "itemqty" + String.valueOf(parmcnt);
                    parmval = req.getParameter(parm);
                    // No more quantity fields, so break out.
                    if ((parmval == null) || parmval.equals("null")) {
                        break;
                    } else // Check quantity value of cart item.
                    {
                        int quantity = Integer.parseInt(parmval);
                        // Quantity set to 0, so remove from cart.
                        if (quantity == 0) {
                            items.remove(cnt);
                        } else // Change quantity of cart item.
                        {
                            si = (ShoppingCartItem) items.get(cnt);
                            si.setQuantity(quantity);
                            items.set(cnt, si);
                            cnt++;
                        }
                    }
                }
                // Are items in cart? Yes, set the session attributes.
                if (items.size() > 0) {
                    shoppingCart.setItems(items);
                    session.setAttribute(Util.ATTR_CART, shoppingCart);
                    session.setAttribute(Util.ATTR_CART_CONTENTS, shoppingCart.getCartContents());
                } else // No items in cart, so remove attributes from session.
                {
                    session.removeAttribute(Util.ATTR_CART);
                    session.removeAttribute(Util.ATTR_CART_CONTENTS);
                }
            } catch (Exception e) {
                //  Log the exception but try to continue.
                Util.debug("ShoppingServlet.performAction() -> Exception caught: " + e);
                // This should take us to the error page.
                throw new ServletException(e.getMessage());
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_INITCHECKOUT)) {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        if (customerInfo == null) {
            req.setAttribute(Util.ATTR_RESULTS, "You must login or register before checking out.");
            session.setAttribute(Util.ATTR_CHECKOUT, new Boolean(true));
            url = Util.PAGE_LOGIN;
        } else {
            url = Util.PAGE_ORDERINFO;
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
    } else if (action.equals(ACTION_ORDERINFODONE)) {
        OrderInfo orderinfo = null;
        ShoppingCart shoppingCart = null;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        String customerID = customerInfo.getCustomerID();
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            Util.debug("orderinfodone: ShoppingCart timeout? check getItems() method");
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("orderinfodone: ShoppingCart ref must have timed out");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            if (cartContents != null) {
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                shoppingCart.setCartContents(cartContents);
            } else {
                Util.debug("NoSuchObject Exception!!!");
                Util.debug("Major Problem!!!");
                shoppingCart = null;
            }
        }
        Util.debug("orderinfodone: got cart?");
        if (shoppingCart != null) {
            Util.debug("orderinfodone: cart not NULL");
            String billName = req.getParameter("bname");
            String billAddr1 = req.getParameter("baddr1");
            String billAddr2 = req.getParameter("baddr2");
            String billCity = req.getParameter("bcity");
            String billState = req.getParameter("bstate");
            String billZip = req.getParameter("bzip");
            String billPhone = req.getParameter("bphone");
            String shipName = req.getParameter("sname");
            String shipAddr1 = req.getParameter("saddr1");
            String shipAddr2 = req.getParameter("saddr2");
            String shipCity = req.getParameter("scity");
            String shipState = req.getParameter("sstate");
            String shipZip = req.getParameter("szip");
            String shipPhone = req.getParameter("sphone");
            int shippingMethod = Integer.parseInt(req.getParameter("shippingMethod"));
            String creditCard = req.getParameter("ccardname");
            String ccNum = req.getParameter("ccardnum");
            String ccExpireMonth = req.getParameter("ccexpiresmonth");
            String ccExpireYear = req.getParameter("ccexpiresyear");
            String cardHolder = req.getParameter("ccholdername");
            orderinfo = shoppingCart.createOrder(customerID, billName, billAddr1, billAddr2, billCity,
                    billState, billZip, billPhone, shipName, shipAddr1, shipAddr2, shipCity, shipState, shipZip,
                    shipPhone, creditCard, ccNum, ccExpireMonth, ccExpireYear, cardHolder, shippingMethod,
                    shoppingCart.getItems());
            Util.debug("orderinfodone: order created");
        }
        if (orderinfo != null) {
            req.setAttribute(Util.ATTR_ORDERINFO, orderinfo);
            req.setAttribute(Util.ATTR_CARTITEMS, shoppingCart.getItems());
            session.setAttribute(Util.ATTR_ORDERKEY, orderinfo.getID());
            requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CHECKOUTFINAL);
        }
    } else if (action.equals(ACTION_COMPLETECHECKOUT)) {
        ShoppingCart shoppingCart = null;
        HttpSession session = req.getSession(true);
        long key = (Long) session.getAttribute(Util.ATTR_ORDERKEY);
        req.setAttribute(Util.ATTR_ORDERID, key);
        long orderKey = key;
        Util.debug("completecheckout: order id =" + orderKey);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        // Check the available inventory and backorder if necessary.
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            Util.debug("completecheckout: ShoppingCart timeout? check getItems() method");
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("completecheckout: ShoppingCart ref must have timed out");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            if (cartContents != null) {
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                shoppingCart.setCartContents(cartContents);
            } else {
                Util.debug("NoSuchObject Exception!!!");
                Util.debug("Major Problem!!!");
                shoppingCart = null;
            }
        }
        if (shoppingCart != null) {
            ShoppingCartItem si;
            Collection items = shoppingCart.getItems();
            for (Object o : items) {
                si = (ShoppingCartItem) o;
                shoppingCart.checkInventory(si);
                Util.debug(
                        "ShoppingCart.checkInventory() - checking Inventory quantity of item: " + si.getID());
            }
        }

        try {
            mailer.createAndSendMail(customerInfo, orderKey);
        } catch (MailerAppException e) {
            System.out.println("MailerAppException:" + e);
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception during create and send mail :" + e);
            e.printStackTrace();
        }
        // Remove items saved in HttpSession.
        session.removeAttribute(Util.ATTR_CART);
        session.removeAttribute(Util.ATTR_CART_CONTENTS);
        session.removeAttribute(Util.ATTR_CATEGORY);
        session.removeAttribute(Util.ATTR_ORDERKEY);
        session.removeAttribute(Util.ATTR_CHECKOUT);
        HttpSession httpSession = req.getSession(true);

        //httpSession.invalidate();
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ORDERDONE);
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.QuestionScoreListener.java

/**
 * This will populate the QuestionScoresBean with the data associated with
 * the particular versioned assessment based on the publishedId.
 * // w ww .j a v  a2s.  co  m
 * @todo Some of this code will change when we move this to Hibernate
 *       persistence.
 * @param publishedId
 *            String
 * @param bean
 *            QuestionScoresBean
 * @return boolean
 */
public boolean questionScores(String publishedId, QuestionScoresBean bean, boolean isValueChange) {
    log.debug("questionScores()");
    try {
        PublishedAssessmentService pubService = new PublishedAssessmentService();
        PublishedItemService pubItemService = new PublishedItemService();
        // get the PublishedAssessment based on publishedId
        QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil.lookupBean("questionScores");
        PublishedAssessmentIfc publishedAssessment = questionBean.getPublishedAssessment();
        if (publishedAssessment == null) {
            publishedAssessment = pubService.getPublishedAssessment(publishedId);
            questionBean.setPublishedAssessment(publishedAssessment);
        }
        // build a hashMap (publishedItemId, publishedItem)
        HashMap publishedItemHash = pubService.preparePublishedItemHash(publishedAssessment);
        log.debug("questionScores(): publishedItemHash.size = " + publishedItemHash.size());
        // build a hashMap (publishedItemTextId, publishedItemText)
        HashMap publishedItemTextHash = pubService.preparePublishedItemTextHash(publishedAssessment);
        log.debug("questionScores(): publishedItemTextHash.size = " + publishedItemTextHash.size());
        HashMap publishedAnswerHash = pubService.preparePublishedAnswerHash(publishedAssessment);
        // re-attach session and load all lazy loaded parent/child stuff

        //         Set<Long> publishedAnswerHashKeySet = publishedAnswerHash.keySet();
        //
        //         for (Long key : publishedAnswerHashKeySet) {
        //            AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(key);
        //
        //            if (!Hibernate.isInitialized(answer.getChildAnswerSet())) {
        //               pubItemService.eagerFetchAnswer(answer);
        //            }
        //         }
        log.debug("questionScores(): publishedAnswerHash.size = " + publishedAnswerHash.size());
        HashMap agentResultsByItemGradingIdMap = new HashMap();

        GradingService delegate = new GradingService();

        TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean("totalScores");

        if (ContextUtil.lookupParam("sortBy") != null && !ContextUtil.lookupParam("sortBy").trim().equals(""))
            bean.setSortType(ContextUtil.lookupParam("sortBy"));

        String itemId = ContextUtil.lookupParam("itemId");
        if (ContextUtil.lookupParam("newItemId") != null
                && !ContextUtil.lookupParam("newItemId").trim().equals("")
                && !ContextUtil.lookupParam("newItemId").trim().equals("null"))
            itemId = ContextUtil.lookupParam("newItemId");

        if (ContextUtil.lookupParam("sortAscending") != null
                && !ContextUtil.lookupParam("sortAscending").trim().equals("")) {
            bean.setSortAscending(Boolean.valueOf(ContextUtil.lookupParam("sortAscending")).booleanValue());
        }

        String which = bean.getAllSubmissions();
        if (which == null && totalBean.getAllSubmissions() != null) {
            // use totalscore's selection
            which = totalBean.getAllSubmissions();
            bean.setAllSubmissions(which);
        }

        totalBean.setSelectedSectionFilterValue(bean.getSelectedSectionFilterValue()); // set section pulldown

        if (bean.getSelectedSARationaleView() == null) {
            // if bean.showSARationaleInLine is null, then set inline to be
            // the default
            bean.setSelectedSARationaleView(QuestionScoresBean.SHOW_SA_RATIONALE_RESPONSES_INLINE);
        }

        if ("true".equalsIgnoreCase(totalBean.getAnonymous())) {
            boolean groupRelease = publishedAssessment.getAssessmentAccessControl().getReleaseTo()
                    .equals(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS);
            if (groupRelease) {
                totalBean.setSelectedSectionFilterValue(TotalScoresBean.RELEASED_SECTIONS_GROUPS_SELECT_VALUE);
            } else {
                totalBean.setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE);
            }
        }

        bean.setPublishedId(publishedId);
        Date dueDate = null;

        HashMap map = getItemScores(Long.valueOf(publishedId), Long.valueOf(itemId), which, isValueChange);
        log.debug("questionScores(): map .size = " + map.size());
        ResourceLoader rb = null;
        ArrayList allscores = new ArrayList();
        Iterator keyiter = map.keySet().iterator();
        while (keyiter.hasNext()) {
            allscores.addAll((ArrayList) map.get(keyiter.next()));
        }

        log.debug("questionScores(): allscores.size = " + allscores.size());

        // /

        // now we need filter by sections selected
        ArrayList scores = new ArrayList(); // filtered list
        Map useridMap = totalBean.getUserIdMap(TotalScoresBean.CALLED_FROM_QUESTION_SCORE_LISTENER);
        bean.setUserIdMap(useridMap);
        log.debug("questionScores(): useridMap.size = " + useridMap.size());

        /*
         * if ("true".equalsIgnoreCase(totalBean.getAnonymous())){ // skip
         * section filter if it is anonymous grading, SAK-4395,
         * scores.addAll(allscores); }
         */
        if (totalBean.getReleaseToAnonymous()) {
            // skip section filter if it's published to anonymous users
            scores.addAll(allscores);
        } else {
            Iterator allscores_iter = allscores.iterator();
            // get the Map of all users(keyed on userid) belong to the
            // selected sections
            while (allscores_iter.hasNext()) {
                // AssessmentGradingData data = (AssessmentGradingData)
                // allscores_iter.next();
                ItemGradingData idata = (ItemGradingData) allscores_iter.next();
                // String agentid =
                // idata.getAssessmentGrading().getAgentId();
                String agentid = idata.getAgentId();
                // now we only include scores of users belong to the
                // selected sections
                if (useridMap.containsKey(agentid)) {
                    scores.add(idata);
                }
            }
        }

        log.debug("questionScores(): scores.size = " + scores.size());

        Iterator iter = scores.iterator();
        ArrayList agents = new ArrayList();

        log.debug("questionScores(): calling populateSections ");

        populateSections(publishedAssessment, bean, totalBean, scores, pubService); // set up the Q1, Q2... links
        if (!iter.hasNext()) {
            // this section has no students
            log.debug("questionScores(): this section has no students");
            bean.setAgents(agents);
            bean.setAllAgents(agents);
            bean.setTotalPeople(Integer.toString(bean.getAgents().size()));
            bean.setAnonymous(totalBean.getAnonymous());
            //return true;
        }

        // List them by item and assessmentgradingid, so we can
        // group answers by item and save them for update use.

        HashMap scoresByItem = new HashMap();
        while (iter.hasNext()) {
            ItemGradingData idata = (ItemGradingData) iter.next();
            ItemTextIfc pubItemText = (ItemTextIfc) publishedItemTextHash.get(idata.getPublishedItemTextId());
            AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash.get(idata.getPublishedAnswerId());

            ArrayList temp = (ArrayList) scoresByItem
                    .get(idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId());
            if (temp == null)
                temp = new ArrayList();

            // Very small numbers, so bubblesort is fast
            Iterator iter2 = temp.iterator();
            ArrayList newList = new ArrayList();
            boolean added = false;
            while (iter2.hasNext()) {
                ItemGradingData tmpData = (ItemGradingData) iter2.next();
                ItemTextIfc tmpPublishedText = (ItemTextIfc) publishedItemTextHash
                        .get(tmpData.getPublishedItemTextId());
                AnswerIfc tmpAnswer = (AnswerIfc) publishedAnswerHash.get(tmpData.getPublishedAnswerId());

                if (pubAnswer != null && tmpAnswer != null && !added && (pubItemText.getSequence()
                        .intValue() < tmpPublishedText.getSequence().intValue()
                        || (pubItemText.getSequence().intValue() == tmpPublishedText.getSequence().intValue()
                                && pubAnswer.getSequence().intValue() < tmpAnswer.getSequence().intValue()))) {
                    newList.add(idata);
                    added = true;
                }
                newList.add(tmpData);
            }
            if (!added)
                newList.add(idata);
            scoresByItem.put(idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId(), newList);
        }
        log.debug("questionScores(): scoresByItem.size = " + scoresByItem.size());
        bean.setScoresByItem(scoresByItem);

        try {
            bean.setAnonymous(publishedAssessment.getEvaluationModel().getAnonymousGrading()
                    .equals(EvaluationModel.ANONYMOUS_GRADING) ? "true" : "false");
        } catch (RuntimeException e) {
            // log.info("No evaluation model.");
            bean.setAnonymous("false");
        }

        // below properties don't seem to be used in jsf pages,
        try {
            bean.setLateHandling(publishedAssessment.getAssessmentAccessControl().getLateHandling().toString());
        } catch (Exception e) {
            // log.info("No access control model.");
            bean.setLateHandling(AssessmentAccessControl.NOT_ACCEPT_LATE_SUBMISSION.toString());
        }
        try {
            bean.setDueDate(publishedAssessment.getAssessmentAccessControl().getDueDate().toString());
            dueDate = publishedAssessment.getAssessmentAccessControl().getDueDate();
        } catch (RuntimeException e) {
            // log.info("No due date.");
            bean.setDueDate(new Date().toString());
        }
        try {
            bean.setMaxScore(publishedAssessment.getEvaluationModel().getFixedTotalScore());
        } catch (RuntimeException e) {
            double score = (double) 0.0;
            Iterator iter2 = publishedAssessment.getSectionArraySorted().iterator();
            while (iter2.hasNext()) {
                SectionDataIfc sdata = (SectionDataIfc) iter2.next();
                Iterator iter3 = sdata.getItemArraySortedForGrading().iterator();
                while (iter3.hasNext()) {
                    ItemDataIfc idata = (ItemDataIfc) iter3.next();
                    if (idata.getItemId().equals(Long.valueOf(itemId)))
                        score = idata.getScore().doubleValue();
                }
            }
            bean.setMaxScore(score);
        }

        // need to get id from somewhere else, not from data. data only
        // contains answered items , we want to return all items.
        // ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(data.getPublishedItemId());
        ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(Long.valueOf(itemId));

        if (item != null) {
            log.debug("item!=null steting type id = " + item.getTypeId().toString());
            bean.setTypeId(item.getTypeId().toString());
            bean.setItemId(item.getItemId().toString());
            bean.setPartName(item.getSection().getSequence().toString());
            bean.setItemName(item.getSequence().toString());
            item.setHint("***"); // Keyword to not show student answer
            // for short answer/ essey question, if there is a model short
            // answer for this question
            // set haveModelShortAnswer to true
            if (item.getTypeId().equals(Long.valueOf(5))) {
                Iterator iterator = publishedAnswerHash.values().iterator();
                while (iterator.hasNext()) {
                    PublishedAnswer publishedAnswer = (PublishedAnswer) iterator.next();
                    if (publishedAnswer.getItem().getItemId().equals(item.getItemId())) {
                        if (publishedAnswer.getText() == null || publishedAnswer.getText().equals("")) {
                            bean.setHaveModelShortAnswer(false);
                        } else {
                            bean.setHaveModelShortAnswer(true);
                        }
                        break;
                    }
                }
            }
        } else {
            log.debug("item==null ");
        }

        ArrayList deliveryItems = new ArrayList(); // so we can use the var
        if (item != null)
            deliveryItems.add(item);
        bean.setDeliveryItem(deliveryItems);

        if (ContextUtil.lookupParam("roleSelection") != null) {
            bean.setRoleSelection(ContextUtil.lookupParam("roleSelection"));
        }

        if (bean.getSortType() == null) {
            if (bean.getAnonymous().equals("true")) {
                bean.setSortType("totalAutoScore");
            } else {
                bean.setSortType("lastName");
            }
        }

        // recordingData encapsulates the inbeanation needed for recording.
        // set recording agent, agent assessmentId,
        // set course_assignment_context value
        // set max tries (0=unlimited), and 30 seconds max length

        // String courseContext = bean.getAssessmentName() + " total ";

        // Note this is HTTP-centric right now, we can't use in Faces
        // AuthoringHelper authoringHelper = new AuthoringHelper();
        // authoringHelper.getRemoteUserID() needs servlet stuff
        // authoringHelper.getRemoteUserName() needs servlet stuff

        /* Dump the grading and agent information into AgentResults */
        iter = scoresByItem.values().iterator();
        while (iter.hasNext()) {
            AgentResults results = new AgentResults();
            // Get all the answers for this question to put in one grading
            // row
            ArrayList answerList = (ArrayList) iter.next();
            results.setItemGradingArrayList(answerList);

            Iterator iter2 = answerList.iterator();
            ArrayList itemGradingAttachmentList = new ArrayList();
            HashMap<Long, Set<String>> fibmap = new HashMap<Long, Set<String>>();
            while (iter2.hasNext()) {
                ItemGradingData gdata = (ItemGradingData) iter2.next();
                results.setItemGrading(gdata);
                itemGradingAttachmentList.addAll(gdata.getItemGradingAttachmentList());
                agentResultsByItemGradingIdMap.put(gdata.getItemGradingId(), results);

                ItemTextIfc gdataPubItemText = (ItemTextIfc) publishedItemTextHash
                        .get(gdata.getPublishedItemTextId());
                AnswerIfc gdataAnswer = (AnswerIfc) publishedAnswerHash.get(gdata.getPublishedAnswerId());

                // This all just gets the text of the answer to display
                String answerText = noAnswer;
                String rationale = "";
                String fullAnswerText = noAnswer;

                // if question type = MC, MR, Survey, TF, Matching, if user
                // has not submit an answer
                // answerText = noAnswer. These question type do not use the
                // itemGrading.answerText field for
                // storing answers, thye use temGrading.publishedAnswerId to
                // make their selection
                if (bean.getTypeId().equals("1") || bean.getTypeId().equals("2")
                        || bean.getTypeId().equals("12") || bean.getTypeId().equals("3")
                        || bean.getTypeId().equals("4") || bean.getTypeId().equals("9")
                        || bean.getTypeId().equals("13")) {
                    if (gdataAnswer != null)
                        answerText = gdataAnswer.getText();
                } else {
                    // this handles the other question types: SAQ, File
                    // upload, Audio, FIB, Fill in Numeric
                    // These question type use itemGrading.answetText to
                    // store information about their answer
                    if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11")
                            || bean.getTypeId().equals("14")) && gdataAnswer == null) {
                        answerText = "";
                    } else if (bean.getTypeId().equals("14")) {//gopalrc - EMI
                        answerText = gdataPubItemText.getSequence() + ": " + gdataAnswer.getLabel();
                    } else {
                        answerText = gdata.getAnswerText();
                    }
                }

                if ("4".equals(bean.getTypeId())) {
                    if (rb == null) {
                        rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
                    }
                    if ("true".equals(answerText)) {
                        answerText = rb.getString("true_msg");
                    } else if ("false".equals(answerText)) {
                        answerText = rb.getString("false_msg");
                    }
                }

                if (bean.getTypeId().equals("9")) {
                    if (gdataPubItemText == null) {
                        // the matching pair is deleted
                        answerText = "";
                    } else {
                        answerText = gdataPubItemText.getSequence() + ":" + answerText;
                    }
                }

                if (bean.getTypeId().equals("8")) {
                    if (gdataAnswer != null && gdataAnswer.getSequence() != null) {
                        answerText = gdataAnswer.getSequence() + ":" + answerText;
                    }
                }

                if (bean.getTypeId().equals("11")) {
                    if (gdataAnswer != null && gdataAnswer.getSequence() != null) {
                        answerText = gdataAnswer.getSequence() + ":" + answerText;
                    }
                }
                if (bean.getTypeId().equals("13")) {
                    if (gdataPubItemText == null) {
                        answerText = "";
                    } else {
                        int answerNo = gdataPubItemText.getSequence().intValue();
                        answerText = answerNo + ":" + answerText;
                    }
                }
                // file upload
                if (bean.getTypeId().equals("6")) {
                    gdata.setMediaArray(delegate.getMediaArray2(gdata.getItemGradingId().toString()));
                }

                // audio recording
                if (bean.getTypeId().equals("7")) {
                    ArrayList mediaList = delegate.getMediaArray2(gdata.getItemGradingId().toString());
                    setDurationIsOver(item, mediaList);
                    gdata.setMediaArray(mediaList);
                }
                if (bean.getTypeId().equals("16")) {
                    if (gdataPubItemText == null) {
                        // the matching pair is deleted
                        answerText = "";
                    } else {
                        answerText = gdataPubItemText.getSequence() + ":" + answerText;
                    }
                }
                if (answerText == null)
                    answerText = noAnswer;
                else {
                    if (gdata.getRationale() != null && !gdata.getRationale().trim().equals(""))
                        rationale = "\nRationale: " + gdata.getRationale();
                }
                // Huong's temp commandout
                // answerText = answerText.replaceAll("<.*?>", "");
                answerText = answerText.replaceAll("(\r\n|\r)", "<br/>");
                rationale = rationale.replaceAll("<.*?>", "");
                rationale = rationale.replaceAll("(\r\n|\r)", "<br/>");
                fullAnswerText = answerText; // this is the
                // non-abbreviated answers
                // for essay questions

                int answerTextLength = ServerConfigurationService
                        .getInt("samigo.questionScore.answerText.length", 1000);
                if (bean.getTypeId().equals("5")) {
                    answerTextLength = 35;
                }

                // Fix for SAK-6932: Strip out all HTML tags except image tags
                if (answerText.length() > answerTextLength) {
                    String noHTMLAnswerText;
                    noHTMLAnswerText = answerText.replaceAll("<((..?)|([^iI][^mM][^gG].*?))>", "");

                    int index = noHTMLAnswerText.toLowerCase().indexOf("<img");
                    if (index != -1) {
                        answerText = noHTMLAnswerText;
                    } else {
                        if (noHTMLAnswerText.length() > answerTextLength) {
                            answerText = noHTMLAnswerText.substring(0, answerTextLength) + "...";
                        } else {
                            answerText = noHTMLAnswerText;
                        }
                    }
                }
                /*
                 * // no need to shorten it if (rationale.length() > 35)
                 * rationale = rationale.substring(0, 35) + "...";
                 */

                //SAM-755-"checkmark" indicates right, add "X" to indicate wrong
                if (gdataAnswer != null) {
                    String checkmarkGif = "<img src='/samigo-app/images/delivery/checkmark.gif'>";
                    String crossmarkGif = "<img src='/samigo-app/images/crossmark.gif'>";

                    if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) {
                        answerText = FormattedText.escapeHtml(answerText, true);
                        if (gdata.getIsCorrect() == null) {
                            boolean result = false;
                            if (bean.getTypeId().equals("8")) {
                                result = delegate.getFIBResult(gdata, fibmap, item, publishedAnswerHash);
                            } else {
                                result = delegate.getFINResult(gdata, item, publishedAnswerHash);
                            }

                            if (result) {
                                answerText = checkmarkGif + answerText;
                            } else {
                                answerText = crossmarkGif + answerText;
                            }
                        } else {
                            if (gdata.getIsCorrect().booleanValue()) {
                                answerText = checkmarkGif + answerText;
                            } else {
                                answerText = crossmarkGif + answerText;
                            }
                        }
                    } else if (bean.getTypeId().equals("15")) { // CALCULATED_QUESTION
                        answerText = FormattedText.escapeHtml(answerText, true);
                        //need to do something here for fill in the blanks
                        if (gdataAnswer.getScore() > 0) {
                            //if score is 0, there is no way to tell if user got the correct answer
                            //by using "autoscore"... wish there was a better way to tell if its correct or not
                            Double autoscore = gdata.getAutoScore();
                            if (!(Double.valueOf(0)).equals(autoscore)) {
                                answerText = checkmarkGif + answerText;
                            } else if (Double.valueOf(0).equals(autoscore)) {
                                answerText = crossmarkGif + answerText;
                            }
                        }
                    } else if (!bean.getTypeId().equals("3")) {
                        if ((gdataAnswer.getIsCorrect() != null && gdataAnswer.getIsCorrect())
                                || (gdataAnswer.getPartialCredit() != null
                                        && gdataAnswer.getPartialCredit() > 0)) {
                            answerText = checkmarkGif + answerText;
                        } else if (gdataAnswer.getIsCorrect() != null && !gdataAnswer.getIsCorrect()) {
                            answerText = crossmarkGif + answerText;
                        }
                    }
                }

                // -- Got the answer text --
                if (!answerList.get(0).equals(gdata)) { // We already have
                    // an agentResults
                    // for this one
                    results.setAnswer(results.getAnswer() + "<br/>" + answerText);
                    if (gdata.getAutoScore() != null) {
                        results.setTotalAutoScore(
                                Double.toString((Double.valueOf(results.getExactTotalAutoScore())).doubleValue()
                                        + gdata.getAutoScore().doubleValue()));
                    } else {
                        results.setTotalAutoScore(Double
                                .toString((Double.valueOf(results.getExactTotalAutoScore())).doubleValue()));
                    }
                    results.setItemGradingAttachmentList(itemGradingAttachmentList);
                } else {
                    results.setItemGradingId(gdata.getItemGradingId());
                    results.setAssessmentGradingId(gdata.getAssessmentGradingId());
                    if (gdata.getAutoScore() != null) {
                        // for example, if an assessment has one fileupload
                        // question, the autoscore = null
                        results.setTotalAutoScore(gdata.getAutoScore().toString());
                    } else {
                        results.setTotalAutoScore(Double.toString(0));
                    }
                    results.setComments(FormattedText.convertFormattedTextToPlaintext(gdata.getComments()));
                    results.setAnswer(answerText);
                    results.setFullAnswer(fullAnswerText);
                    results.setRationale(rationale);
                    results.setSubmittedDate(gdata.getSubmittedDate());

                    AgentFacade agent = new AgentFacade(gdata.getAgentId());
                    // log.info("Rachel: agentid = " + gdata.getAgentId());
                    results.setLastName(agent.getLastName());
                    results.setFirstName(agent.getFirstName());
                    results.setEmail(agent.getEmail());
                    if (results.getLastName() != null && results.getLastName().length() > 0)
                        results.setLastInitial(results.getLastName().substring(0, 1));
                    else if (results.getFirstName() != null && results.getFirstName().length() > 0)
                        results.setLastInitial(results.getFirstName().substring(0, 1));
                    else
                        results.setLastInitial("Anonymous");
                    results.setIdString(agent.getIdString());
                    results.setAgentEid(agent.getEidString());
                    results.setAgentDisplayId(agent.getDisplayIdString());
                    log.debug("testing agent getEid agent.getFirstname= " + agent.getFirstName());
                    log.debug("testing agent getEid agent.getid= " + agent.getIdString());
                    log.debug("testing agent getEid agent.geteid = " + agent.getEidString());
                    log.debug("testing agent getDisplayId agent.getdisplayid = " + agent.getDisplayIdString());

                    results.setRole(agent.getRole());
                    results.setItemGradingAttachmentList(itemGradingAttachmentList);
                    agents.add(results);
                }
            }
        }

        // log.info("Sort type is " + bean.getSortType() + ".");
        bs = new BeanSort(agents, bean.getSortType());
        if ((bean.getSortType()).equals("assessmentGradingId") || (bean.getSortType()).equals("totalAutoScore")
                || (bean.getSortType()).equals("totalOverrideScore")
                || (bean.getSortType()).equals("finalScore")) {
            bs.toNumericSort();
        } else {
            bs.toStringSort();
        }

        if (bean.isSortAscending()) {
            log.debug("sortAscending");
            agents = (ArrayList) bs.sort();
        } else {
            log.debug("!sortAscending");
            agents = (ArrayList) bs.sortDesc();
        }

        // log.info("Listing agents.");
        bean.setAgents(agents);
        bean.setAllAgents(agents);
        bean.setTotalPeople(Integer.valueOf(bean.getAgents().size()).toString());
        bean.setAgentResultsByItemGradingId(agentResultsByItemGradingIdMap);
    }

    catch (RuntimeException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.android.vending.billing.InAppBillingService.LACK.listAppsFragment.java

public static void removeDialogAll(int paramInt) {
      try {/*from  w w  w.  j a  va  2  s .c o  m*/
          if (all_d != null) {
              if (all_d.dialog_int == paramInt) {
                  all_d.dismiss();
              }
              all_d = null;
          }
          return;
      } catch (RuntimeException localRuntimeException) {
          localRuntimeException.printStackTrace();
          return;
      } catch (Exception localException) {
          localException.printStackTrace();
      }
  }

From source file:com.android.vending.billing.InAppBillingService.LACK.listAppsFragment.java

public static void removeDialogLP(int paramInt) {
      switch (paramInt) {
      default://from   www . j  a  v  a 2s.  c  om
      case 23:
      case 1:
          try {
              if (all_d == null) {
                  break;
              }
              if (all_d.dialog_int == paramInt) {
                  all_d.dismiss();
              }
              all_d = null;
              return;
          } catch (RuntimeException localRuntimeException) {
              localRuntimeException.printStackTrace();
              return;
              if (progress == null) {
                  break;
              }
              progress.dismiss();
              progress = null;
              return;
          } catch (Exception localException) {
              localException.printStackTrace();
              return;
          }
          if (progress_loading != null) {
              progress_loading.dismiss();
              progress_loading = null;
              return;
          }
          break;
      case 11:
          if (progress2 != null) {
              progress2.dismiss();
              progress2 = null;
              return;
          }
          break;
      case 6:
          if (app_d != null) {
              app_d.dismiss();
              app_d = null;
              return;
          }
          break;
      case 2:
          if (patch_d != null) {
              patch_d.dismiss();
              patch_d = null;
              return;
          }
          break;
      case 7:
          if (menu_d != null) {
              menu_d.dismiss();
              menu_d = null;
              return;
          }
          break;
      case 38:
          if (menu_d_static != null) {
              menu_d_static.dismiss();
              menu_d_static = null;
              return;
          }
          break;
      case 4:
          if (c_p_d != null) {
              c_p_d.dismiss();
              c_p_d = null;
              return;
          }
          break;
      case 15:
          if (c2_d != null) {
              c2_d.dismiss();
              c2_d = null;
              return;
          }
          break;
      case 8:
          if (c_a_d != null) {
              c_a_d.dismiss();
              c_a_d = null;
          }
          break;
      }
  }

From source file:com.android.vending.billing.InAppBillingService.LACK.listAppsFragment.java

public static void showDialogLP(int paramInt) {
      switch (paramInt) {
      default://from w  w  w.  j a v a2s . com
      case 23:
          try {
              System.out.println("dialog " + paramInt);
              if (all_d != null) {
                  if (all_d.isVisible()) {
                      all_d.dismiss();
                  }
                  all_d = null;
              }
              all_d = new All_Dialogs();
              dialog_int = paramInt;
              all_d.dialog_int = paramInt;
              all_d.showDialog();
              return;
          } catch (RuntimeException localRuntimeException) {
              localRuntimeException.printStackTrace();
              return;
              progress_loading = Progress_Dialog_Loading.newInstance();
              progress_loading.showDialog();
              return;
          } catch (Exception localException) {
              localException.printStackTrace();
              return;
          }
          if (progress_loading != null) {
              progress_loading.dismiss();
              progress_loading = null;
              progress_loading = Progress_Dialog_Loading.newInstance();
              progress_loading.showDialog();
              return;
          }
      case 1:
          if (progress != null) {
              progress.dismiss();
              progress = null;
              progress = Progress_Dialog.newInstance();
              progress.showDialog();
              return;
          }
          progress = Progress_Dialog.newInstance();
          progress.showDialog();
          return;
      case 11:
          if (progress2 != null) {
              progress2.dismiss();
              progress2 = null;
              progress2 = Progress_Dialog_2.newInstance();
              progress2.showDialog();
              return;
          }
          progress2 = Progress_Dialog_2.newInstance();
          progress2.showDialog();
          return;
      case 6:
          if (app_d != null) {
              app_d.dismiss();
              app_d = null;
          }
          app_d = new App_Dialog();
          app_d.showDialog();
          return;
      case 2:
          if (patch_d != null) {
              patch_d.dismiss();
              patch_d = null;
          }
          patch_d = new Patch_Dialog();
          patch_d.showDialog();
          return;
      case 40:
          if (integrate_d != null) {
              integrate_d.dismiss();
              integrate_d = null;
          }
          integrate_d = new Integrate_Dalvik_Code_Dialog();
          integrate_d.showDialog();
          return;
      case 7:
          if (menu_d != null) {
              menu_d.dismiss();
              menu_d = null;
          }
          menu_d = new Menu_Dialog();
          menu_d.showDialog();
          return;
      case 38:
          if (menu_d_static != null) {
              menu_d_static.dismiss();
              menu_d_static = null;
          }
          menu_d_static = new Menu_Dialog_Static();
          menu_d_static.showDialog();
          return;
      case 4:
          if (c_p_d != null) {
              c_p_d.dismiss();
              c_p_d = null;
          }
          c_p_d = new Custom_Patch_Dialog();
          c_p_d.showDialog();
          return;
      case 15:
          if (c2_d != null) {
              c2_d.dismiss();
              c2_d = null;
          }
          c2_d = new Custom2_Dialog();
          c2_d.showDialog();
          return;
      case 8:
          if (c_a_d != null) {
              c_a_d.dismiss();
              c_a_d = null;
          }
          c_a_d = new Create_Apk_Dialog();
          c_a_d.showDialog();
          return;
      case 9:
          if (c_a_a_d != null) {
              c_a_a_d.dismiss();
              c_a_a_d = null;
          }
          c_a_a_d = new Create_Apk_Ads_Dialog();
          c_a_a_d.showDialog();
          return;
      case 36:
          if (c_a_s_d != null) {
              c_a_s_d.dismiss();
              c_a_s_d = null;
          }
          c_a_s_d = new Create_Apk_Support_Dialog();
          c_a_s_d.showDialog();
          return;
      case 5:
          if (e_p_d != null) {
              e_p_d.dismiss();
              e_p_d = null;
          }
          e_p_d = new Ext_Patch_Dialog();
          e_p_d.showDialog();
          return;
      }
      if (m_i_d != null) {
          m_i_d.dismiss();
          m_i_d = null;
      }
      m_i_d = new Market_Install_Dialog();
      m_i_d.showDialog();
  }