Example usage for org.apache.commons.lang3 StringEscapeUtils escapeHtml3

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeHtml3

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeHtml3.

Prototype

public static final String escapeHtml3(final String input) 

Source Link

Document

Escapes the characters in a String using HTML entities.

Supports only the HTML 3.0 entities.

Usage

From source file:com.aurel.track.exchange.docx.exporter.CustomXML.java

/**
 * Add watcher nodes to xml/*from ww w .  j av a2  s  . co m*/
 * @param watcherPersonBeans
 * @param root
 * @param dom
 * @param commentsName
 * @param watcherElement
 */
private static void addCommentNodes(List<HistoryValues> comments, Element root, Document dom, Locale locale) {
    if (comments == null || comments.isEmpty()) {
        appendChild(root, CUSTOM_XML_ELEMENTS.COMMENTS + CUSTOM_XML_ELEMENTS.PRESENT_SUFFIX,
                Boolean.FALSE.toString(), dom);
    } else {
        Element consultedList = dom.createElement(CUSTOM_XML_ELEMENTS.COMMENTS);
        for (HistoryValues historyValue : comments) {
            String commentText = historyValue.getNewShowValue();
            commentText = StringEscapeUtils.escapeHtml3(commentText);
            Element commentTextElement = createDomElement(CUSTOM_XML_ELEMENTS.COMMENT_TEXT, commentText, dom);
            Element commentedByElement = createDomElement(CUSTOM_XML_ELEMENTS.COMMENTED_BY,
                    historyValue.getChangedByName(), dom);
            Element commentedAtElement = createDomElement(CUSTOM_XML_ELEMENTS.COMMENTED_AT,
                    DateTimeUtils.getInstance().formatGUIDate(historyValue.getLastEdit(), locale), dom);
            Element commentElement = createDomElement(CUSTOM_XML_ELEMENTS.COMMENT, "", dom);
            commentElement.appendChild(commentTextElement);
            commentElement.appendChild(commentedByElement);
            commentElement.appendChild(commentedAtElement);
            consultedList.appendChild(commentElement);
        }
        root.appendChild(consultedList);
        appendChild(root, CUSTOM_XML_ELEMENTS.COMMENTS + CUSTOM_XML_ELEMENTS.PRESENT_SUFFIX,
                Boolean.TRUE.toString(), dom);
    }
}

From source file:de.cebitec.readXplorer.util.GeneralUtils.java

public static String escapeHtml(String s) {
    return StringEscapeUtils.escapeHtml3(s);
}

From source file:com.fanniemae.ezpie.LogManager.java

protected void updateLog(Boolean isError, String logGroup, String event, String description, String cargo,
        Boolean preserveLayout, Boolean isHTML) {
    if (!isError && (_logLevel == LogLevel.ERROR_ONLY)) {
        return;/*  w  ww.j  a  va 2 s  .  c o m*/
    }

    // Skip blank description messages
    if (description == null) {
        return;
    }
    if (!FileUtilities.isValidFile(_logFilename)) {
        initializeLog();
    }

    // Encode the description line and preserve any CRLFs.
    if (isHTML) {
        // do nothing
    } else if (_logFormat == LogFormat.TEXT) {
        // do nothing
    } else if (preserveLayout) {
        description = StringEscapeUtils.escapeHtml3(description).replace(" ", "&nbsp;").replace("\n", _newLine);
    } else {
        description = StringEscapeUtils.escapeHtml3(description).replace("\n", _newLine);
    }

    if ((_logFormat == LogFormat.HTML) && cargo.startsWith("file://")) {
        // add html link line to view the file.
        String fileName = FileUtilities.getFilenameOnly(cargo.substring(7));
        description = String.format("<a href=\"%2$s\">%1$s</a>", description, fileName);
    } else if (cargo.startsWith("file://")) {
        description = String.format("%1$s %2$s", description, cargo.substring(7));
    }

    try (RandomAccessFile raf = new RandomAccessFile(_logFilename, "rw")) {
        raf.seek(raf.length() - _footerLength);
        if (isError) {
            raf.write(String.format(_exceptionRow, groupString(logGroup), event, description, elapsedTime())
                    .getBytes());
        } else if ((description != null) && (description.length() > 300)) {
            raf.write(String.format(_longTextLine, groupString(logGroup), event, description, elapsedTime())
                    .getBytes());
        } else {
            raf.write(String.format(_basicLine, groupString(logGroup), event, description, elapsedTime())
                    .getBytes());
        }

        // raf.write("\n".getBytes());
        raf.write(_footerByteArray);
    } catch (IOException e) {
        throw new PieException("Error trying to add message to debug page.", e);
    }
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * <p>//from   w w w  . ja va2 s  .co m
 * escape HTML see StringEscapeUtils.escapeHtml3(str)
 * </p>
 * <p>
 * Supports all known HTML 3.0 entities, including funky accents. Note that
 * the commonly used apostrophe escape character (&amp;apos;) is not a legal
 * entity and so is not supported).
 * </p>
 * <p>
 * For example:
 * </p>
 * <p>
 * <code>"bread" &amp; "butter"</code>
 * </p>
 * becomes:
 * <p>
 * <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code>
 * .
 * </p>
 *
 * @param str value
 * @return string
 */
public static String escapeHtml3(String str) {
    if (isBlank(str)) {
        return str;
    }
    return StringEscapeUtils.escapeHtml3(str);
}

From source file:com.trsst.Common.java

public static String escapeHTML(String html) {
    return StringEscapeUtils.escapeHtml3(html);
}

From source file:cn.sinobest.jzpt.framework.utils.string.StringUtils.java

/**
 * HTML/*from   w w w.  ja  va2  s.c o m*/
 */
public static CharSequence escapeHtml(CharSequence s, boolean unicode) {
    if (unicode)
        return StringEscapeUtils.escapeHtml3(s.toString());
    StringBuilder sb = new StringBuilder(s.length() + 16);
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        int n = htmlEscEntities.indexOf(c);
        if (n > -1) {
            sb.append(htmlEscapeSequence[n]);
        } else {
            sb.append(c);
        }
    }
    return sb.length() == s.length() ? s : sb.toString();// string
}

From source file:com.rr.missouri.ui.surveys.surveyController.java

/**
 * The '/takeSurvey' POST request will submit the survey page.
 *
 * @param survey/*from  w ww  .ja  v a 2 s  . c om*/
 * @param session
 * @param redirectAttr
 * @param action
 * @param goToPage
 * @param disabled
 * @param selectedEntities
 * @param entityIds
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/submitSurvey", method = RequestMethod.POST)
public ModelAndView saveSurveyPage(@ModelAttribute(value = "survey") survey survey, HttpSession session,
        RedirectAttributes redirectAttr, @RequestParam String action, @RequestParam Integer goToPage,
        @RequestParam(value = "entityIds", required = false) List<String> entityIds,
        @RequestParam(value = "selectedEntities", required = false) List<String> selectedEntities,
        @RequestParam(value = "disabled", required = true, defaultValue = "false") boolean disabled,
        @RequestParam(value = "currPageNum", required = true) int currPageNum) throws Exception {

    Integer goToQuestion = 0;
    boolean skipToEnd = false;
    boolean submitted = false;

    ModelAndView mav = new ModelAndView();

    if (entityIds != null && !"".equals(entityIds) && !entityIds.isEmpty()) {
        List<Integer> entityIdList = new ArrayList<Integer>();

        for (String entityId : entityIds) {
            Integer entityIdasInt = Integer.parseInt(entityId);

            entityIdList.add(entityIdasInt);
        }
        survey.setEntityIds(entityIdList);
    }

    Integer lastQuestionSavedId = 0;
    Integer lastPageSaved = 0;

    if ("next".equals(action) || "done".equals(action) || "save".equals(action)) {
        goToPage = 0;
        Integer lastQuestionSaved = 0;
        List<SurveyQuestions> questions = survey.getSurveyPageQuestions();

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : questions) {

            boolean questionFound = false;

            List<surveyQuestionAnswers> toRemove = new ArrayList<surveyQuestionAnswers>();

            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {

                    surveyQuestionAnswers questionAnswer = it.next();

                    if ((questionAnswer.getPageNum() > currPageNum)) {
                        questionAnswer.setSaveToDB(false);
                    }

                    if (questionAnswer.getQuestionId() == question.getId()) {

                        if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                                && question.getQuestionValue().contains(",")) {
                            toRemove.add(questionAnswer);
                        } else {
                            questionFound = true;

                            if (question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2) {
                                SurveyQuestionChoices choiceDetails = surveyManager
                                        .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));

                                if (choiceDetails.getChoiceValue() > 0) {
                                    questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                } /*else {
                                  questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                                  }*/
                                questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                if (choiceDetails.isSkipToEnd() == true) {
                                    skipToEnd = true;
                                    submitted = true;
                                    lastPageSaved = question.getSurveyPageId();
                                } else {
                                    if (choiceDetails.getSkipToPageId() > 0) {
                                        SurveyPages pageDetails = surveyManager
                                                .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                        goToPage = pageDetails.getPageNum();
                                    }

                                    goToQuestion = choiceDetails.getSkipToQuestionId();

                                    lastQuestionSavedId = question.getId();
                                }

                                questionAnswer.setAnswerOther(question.getQuestionOtherValue());

                            } else {
                                questionAnswer.setAnswerText(question.getQuestionValue());
                            }

                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);
                        }
                    }
                }
            }
            if (!toRemove.isEmpty()) {
                questionAnswers.removeAll(toRemove);
            }

            if (questionFound == false) {

                if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                        && !"".equals(question.getQuestionValue())) {

                    if (question.getQuestionValue().contains(",")) {
                        String[] lineVector = question.getQuestionValue().split(",");

                        for (int i = 0; i < lineVector.length; i++) {
                            surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();
                            Integer qAnsValue = Integer.parseInt(lineVector[i]);

                            SurveyQuestionChoices choiceDetails = surveyManager
                                    .getSurveyQuestionChoice(qAnsValue);

                            if (choiceDetails.getChoiceValue() > 0) {
                                questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                            } /*else {
                              questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                              }*/
                            questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                            if (choiceDetails.isSkipToEnd() == true) {
                                skipToEnd = true;
                                submitted = true;
                                lastPageSaved = question.getSurveyPageId();
                            } else {
                                if (choiceDetails.getSkipToPageId() > 0) {
                                    SurveyPages pageDetails = surveyManager
                                            .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                    goToPage = pageDetails.getPageNum();
                                }

                                goToQuestion = choiceDetails.getSkipToQuestionId();

                                lastQuestionSavedId = question.getId();
                            }

                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);

                            questionAnswers.add(questionAnswer);

                            if (i == 0) {
                                questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                            }

                        }

                    } else {

                        surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                        boolean isInt = true;

                        try {
                            Integer.parseInt(question.getQuestionValue());
                        } catch (NumberFormatException e) {
                            isInt = false;
                        } catch (NullPointerException e) {
                            isInt = false;
                        }

                        if (isInt) {
                            SurveyQuestionChoices choiceDetails = surveyManager
                                    .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));
                            if (choiceDetails.getChoiceValue() > 0) {
                                questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                            } /*else {
                              questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                              }*/
                            questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                            if (choiceDetails.isSkipToEnd() == true) {
                                skipToEnd = true;
                                submitted = true;
                                lastPageSaved = question.getSurveyPageId();
                            } else {
                                if (choiceDetails.getSkipToPageId() > 0) {
                                    SurveyPages pageDetails = surveyManager
                                            .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                    goToPage = pageDetails.getPageNum();
                                }

                                goToQuestion = choiceDetails.getSkipToQuestionId();

                                lastQuestionSavedId = question.getId();
                            }

                        } else {
                            questionAnswer.setAnswerText(question.getQuestionValue());
                        }

                        questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                        questionAnswer.setQuestionId(question.getId());
                        questionAnswer.setProgramPatientId(survey.getClientId());
                        questionAnswer.setProgramEngagementId(survey.getEngagementId());
                        questionAnswer.setqNum(question.getQuestionNum());
                        questionAnswer.setSurveyPageId(question.getSurveyPageId());
                        questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                        questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                        questionAnswer.setSaveToDB(true);
                        questionAnswer.setPageNum(currPageNum);

                        questionAnswers.add(questionAnswer);
                    }

                } else {
                    surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                    questionAnswer.setAnswerText(question.getQuestionValue());

                    questionAnswer.setQuestionId(question.getId());
                    questionAnswer.setProgramPatientId(survey.getClientId());
                    questionAnswer.setProgramEngagementId(survey.getEngagementId());
                    questionAnswer.setqNum(question.getQuestionNum());
                    questionAnswer.setSurveyPageId(question.getSurveyPageId());
                    questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                    questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                    questionAnswer.setSaveToDB(true);
                    questionAnswer.setPageNum(currPageNum);

                    questionAnswers.add(questionAnswer);
                }

            }

            lastQuestionSaved = question.getQuestionNum();
        }

        /* Remove questions passed the last question answered */
        List<surveyQuestionAnswers> updatedquestionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Iterator<surveyQuestionAnswers> itr = updatedquestionAnswers.iterator();

        while (itr.hasNext()) {
            surveyQuestionAnswers questionAnswer = itr.next();

            if (questionAnswer.getqNum() > lastQuestionSaved) {
                itr.remove();
            }
        }

    }

    survey NextPage = new survey();
    NextPage.setClientId(survey.getClientId());
    NextPage.setSurveyId(survey.getSurveyId());
    NextPage.setSurveyTitle(survey.getSurveyTitle());
    NextPage.setPrevButton(survey.getPrevButton());
    NextPage.setNextButton(survey.getNextButton());
    NextPage.setSaveButton(survey.getSaveButton());
    NextPage.setSubmittedSurveyId(survey.getSubmittedSurveyId());
    NextPage.setEntityIds(survey.getEntityIds());

    SurveyPages currentPage = null;
    Integer qNum = 1;
    Integer nextPage = 1;

    /* Get the pages */
    List<SurveyPages> surveyPages = surveyManager.getSurveyPages(survey.getSurveyId(), false, 0, 0, 0);

    if ("prev".equals(action)) {
        mav.setViewName("/takeSurvey");

        currPageNum--;
        mav.addObject("currPageNum", currPageNum);

        List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");

        nextPage = seenPages.get(seenPages.size() - 1);
        /* Remove this page from array */
        seenPages.remove(seenPages.size() - 1);

        currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId);

        Integer totalPageQuestions = 0;

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
            question.setQuestionValue("");
            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {
                        if ("".equals(question.getQuestionValue())) {
                            question.setQuestionValue(questionAnswer.getAnswerText());
                            if (!"".equals(questionAnswer.getAnswerOther())) {
                                question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                            }
                        } else {
                            String currValue = question.getQuestionValue();
                            currValue += ",";
                            currValue += questionAnswer.getAnswerText();
                            question.setQuestionValue(currValue);
                        }
                    }
                }
            }

            if (question.getAnswerTypeId() != 7) {
                totalPageQuestions += 1;
            }
        }

        qNum = (survey.getLastQNumAnswered() - totalPageQuestions) - 1;
    } else if ("next".equals(action)) {
        mav.setViewName("/takeSurvey");

        currPageNum++;
        mav.addObject("currPageNum", currPageNum);

        if (goToPage > 0) {
            nextPage = goToPage;
        } else {

            /* Check to see if page has any skip logic */
            SurveyPages currentPageDetails = surveyManager.getSurveyPageDetails(survey.getPageId());
            if (currentPageDetails.getSkipToPage() > 0) {
                SurveyPages skiptoPageDetails = surveyManager
                        .getSurveyPageDetails(currentPageDetails.getSkipToPage());
                nextPage = skiptoPageDetails.getPageNum();
            } else if (currentPageDetails.getSkipToPage() == -1) {
                skipToEnd = true;
                submitted = true;
            } else {
                nextPage = survey.getCurrentPage() + 1;
            }
        }

        List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");
        seenPages.add(survey.getCurrentPage());

        currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId);

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
            String currDBValue = question.getQuestionValue();
            String currDBOtherValue = question.getQuestionOtherValue();
            question.setQuestionValue("");
            question.setQuestionOtherValue("");
            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {
                        if ("".equals(question.getQuestionValue())) {
                            question.setQuestionValue(questionAnswer.getAnswerText());
                            if (!"".equals(questionAnswer.getAnswerOther())) {
                                question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                            }
                        } else {
                            String currValue = question.getQuestionValue();
                            currValue += ",";
                            currValue += questionAnswer.getAnswerText();
                            question.setQuestionValue(currValue);
                        }
                    }
                }
            }

            if ("".equals(question.getQuestionValue())) {
                question.setQuestionValue(currDBValue);
                if ("".equals(question.getQuestionOtherValue())) {
                    question.setQuestionOtherValue(currDBOtherValue);
                }
            }
        }

        qNum = survey.getLastQNumAnswered();

    } else if ("save".equals(action)) {
        submitted = false;
    } else if ("done".equals(action)) {
        skipToEnd = true;
        submitted = true;
    }

    /**
     * If saving the survey, save and redirect to the survey list page *
     */
    if ("save".equals(action)) {
        User userDetails = (User) session.getAttribute("userDetails");

        /**
         * Submit answers to DB *
         */
        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                questionAnswers, submitted, selectedEntities);

        //if (surveyContentCriterias != null) {
        if (session.getAttribute("selectedContentCriterias") != null) {
            List<surveyContentCriteria> selectedContentCriteria = (List<surveyContentCriteria>) session
                    .getAttribute("selectedContentCriterias");

            Iterator<surveyContentCriteria> it = selectedContentCriteria.iterator();

            /* Delete existing code sets */
            surveyManager.deleteSurveyCodeSets(submittedSurveyId);

            while (it.hasNext()) {

                surveyContentCriteria criteria = it.next();

                if (criteria.isChecked()) {
                    submittedsurveycontentcriteria savedCodeSets = new submittedsurveycontentcriteria();
                    savedCodeSets.setCodeId(criteria.getCodeId());
                    savedCodeSets.setEntityId(criteria.getSchoolId());
                    savedCodeSets.setSubmittedSurveyId(submittedSurveyId);

                    surveyManager.submitSurveyCodeSets(savedCodeSets);
                }
            }
        }

        encryptObject encrypt = new encryptObject();
        Map<String, String> map;

        //Encrypt the use id to pass in the url
        map = new HashMap<String, String>();
        map.put("id", Integer.toString(survey.getSurveyId()));
        map.put("topSecret", topSecret);

        String[] encrypted = encrypt.encryptObject(map);

        mav = new ModelAndView(new RedirectView("/surveys?i=" + encrypted[0] + "&v=" + encrypted[1]));
    } /**
      * If reached the last page or an option was selected to skip to the end *
      */
    else if (currentPage == null || skipToEnd == true) {

        if (disabled == false) {
            User userDetails = (User) session.getAttribute("userDetails");

            /* If skipToEnd == true && submitted == true we need to remove any questions that 
            appear after the last saved page
            */
            if (skipToEnd == true && submitted == true && lastPageSaved > 0
                    && survey.getSubmittedSurveyId() > 0) {
                surveyManager.removeOldAnswers(survey.getSubmittedSurveyId(), lastPageSaved);
            }

            /**
             * Submit answers to DB *
             */
            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");
            Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                    questionAnswers, submitted, selectedEntities);

            if (session.getAttribute("selectedContentCriterias") != null) {
                List<surveyContentCriteria> selectedContentCriteria = (List<surveyContentCriteria>) session
                        .getAttribute("selectedContentCriterias");

                Iterator<surveyContentCriteria> it = selectedContentCriteria.iterator();

                /* Delete existing code sets */
                surveyManager.deleteSurveyCodeSets(submittedSurveyId);

                while (it.hasNext()) {

                    surveyContentCriteria criteria = it.next();

                    if (criteria.isChecked()) {
                        submittedsurveycontentcriteria savedCodeSets = new submittedsurveycontentcriteria();
                        savedCodeSets.setCodeId(criteria.getCodeId());
                        savedCodeSets.setEntityId(criteria.getSchoolId());
                        savedCodeSets.setSubmittedSurveyId(submittedSurveyId);

                        surveyManager.submitSurveyCodeSets(savedCodeSets);
                    }
                }
            }

            encryptObject encrypt = new encryptObject();
            Map<String, String> map1;
            Map<String, String> map2;

            //Encrypt the use id to pass in the url
            map1 = new HashMap<String, String>();
            map1.put("id", Integer.toString(survey.getSurveyId()));
            map1.put("topSecret", topSecret);

            //Encrypt the use id to pass in the url
            map2 = new HashMap<String, String>();
            map2.put("id", Integer.toString(submittedSurveyId));
            map2.put("topSecret", topSecret);

            String[] encrypted = encrypt.encryptObject(map1);
            String[] encrypted2 = encrypt.encryptObject(map2);

            /** Check to see if this program has access to the document module **/
            boolean hasDocumentModule = false;
            String[][] availablePrograms = (String[][]) session.getAttribute("availModules");

            for (int p = 0; p < availablePrograms.length; p++) {
                if (Integer.parseInt(availablePrograms[p][3]) == 10) {
                    hasDocumentModule = true;
                }
            }

            mav.addObject("hasDocumentModule", hasDocumentModule);

            mav.setViewName("/completedSurvey");
            surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());
            mav.addObject("surveyDetails", surveyDetails);

            List<district> districtList = (List<district>) session.getAttribute("districtList");
            mav.addObject("selDistricts", districtList);
            mav.addObject("surveys", surveys);
            mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));
            mav.addObject("i", encrypted[0]);
            mav.addObject("v", encrypted[1]);
            mav.addObject("i2", encrypted2[0]);
            mav.addObject("v2", encrypted2[1]);
            mav.addObject("submittedSurveyId", submittedSurveyId);

            /* Get a list of survey documents */
            List<submittedSurveyDocuments> surveyDocuments = surveyManager
                    .getSubmittedSurveyDocuments(submittedSurveyId);

            if (surveyDocuments != null && surveyDocuments.size() > 0) {
                for (submittedSurveyDocuments document : surveyDocuments) {
                    if (document.getUploadedFile() != null && !"".equals(document.getUploadedFile())) {
                        int index = document.getUploadedFile().lastIndexOf('.');
                        document.setFileExt(document.getUploadedFile().substring(index + 1));

                        if (document.getUploadedFile().length() > 60) {
                            String shortenedTitle = document.getUploadedFile().substring(0, 30) + "..."
                                    + document.getUploadedFile().substring(
                                            document.getUploadedFile().length() - 10,
                                            document.getUploadedFile().length());
                            document.setShortenedTitle(shortenedTitle);
                        }
                        document.setEncodedTitle(URLEncoder.encode(document.getUploadedFile(), "UTF-8"));

                    }
                }
            }

            mav.addObject("surveyDocuments", surveyDocuments);

        } else {

        }

    } else {

        NextPage.setPageTitle(currentPage.getPageTitle());
        NextPage.setPageDesc(currentPage.getPageDesc());
        NextPage.setSurveyPageQuestions(currentPage.getSurveyQuestions());
        NextPage.setPageId(currentPage.getId());

        /* Loop through to get actually question answers */

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {

            String questionValue = "";

            while (it.hasNext()) {
                surveyQuestionAnswers questionAnswer = it.next();

                if (questionAnswer.getQuestionId() == question.getId()) {

                    if (questionAnswer != null) {
                        if (questionAnswer.getAnswerId() > 0) {
                            questionValue += String.valueOf(questionAnswer.getAnswerId());
                        } else {
                            questionValue += questionAnswer.getAnswerText();
                        }

                        questionValue += ",";
                    }
                }
            }

            if (!"".equals(questionValue)) {
                question.setQuestionValue(StringEscapeUtils.escapeHtml3(questionValue.replaceAll("(,)*$", "")));
            }
        }

        NextPage.setTotalPages(surveyPages.size());
        NextPage.setCurrentPage(nextPage);
        NextPage.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

        mav.addObject("survey", NextPage);
        mav.addObject("surveyPages", surveyPages);
        mav.addObject("qNum", qNum);
        mav.addObject("selectedEntities", selectedEntities);
        List<district> districtList = (List<district>) session.getAttribute("districtList");
        mav.addObject("selDistricts", districtList);
        mav.addObject("surveys", surveys);
        mav.addObject("disabled", disabled);
        mav.addObject("selSurvey", survey.getSurveyId());
    }

    return mav;
}

From source file:com.rr.moheals.ui.surveys.surveyController.java

/**
 * The '/takeSurvey' POST request will submit the survey page.
 *
 * @param survey/*from w w  w. j a  va  2  s  .  com*/
 * @param session
 * @param redirectAttr
 * @param action
 * @param goToPage
 * @param disabled
 * @param selectedEntities
 * @param entityIds
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/submitSurvey", method = RequestMethod.POST)
public ModelAndView saveSurveyPage(@ModelAttribute(value = "survey") survey survey, HttpSession session,
        RedirectAttributes redirectAttr, @RequestParam String action, @RequestParam Integer goToPage,
        @RequestParam(value = "entityIds", required = false) List<String> entityIds,
        @RequestParam(value = "selectedEntities", required = false) List<String> selectedEntities,
        @RequestParam(value = "disabled", required = true, defaultValue = "false") boolean disabled,
        @RequestParam(value = "currPageNum", required = true) int currPageNum) throws Exception {

    Integer goToQuestion = 0;
    boolean skipToEnd = false;
    boolean submitted = false;

    ModelAndView mav = new ModelAndView();

    if (entityIds != null && !"".equals(entityIds) && !entityIds.isEmpty()) {
        List<Integer> entityIdList = new ArrayList<Integer>();

        for (String entityId : entityIds) {
            Integer entityIdasInt = Integer.parseInt(entityId);

            entityIdList.add(entityIdasInt);
        }
        survey.setEntityIds(entityIdList);
    }

    Integer lastQuestionSavedId = 0;
    Integer lastPageSaved = 0;

    if ("next".equals(action) || "done".equals(action) || "save".equals(action)) {

        goToPage = 0;
        Integer lastQuestionSaved = 0;
        List<SurveyQuestions> questions = survey.getSurveyPageQuestions();

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : questions) {

            boolean questionFound = false;

            List<surveyQuestionAnswers> toRemove = new ArrayList<surveyQuestionAnswers>();

            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if ((questionAnswer.getPageNum() > currPageNum)) {
                        questionAnswer.setSaveToDB(false);
                    }

                    if (questionAnswer.getQuestionId() == question.getId()) {

                        if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                                && question.getQuestionValue().contains(",")) {
                            toRemove.add(questionAnswer);
                        } else {

                            questionFound = true;

                            if (question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2) {

                                SurveyQuestionChoices choiceDetails = surveyManager
                                        .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));

                                if (choiceDetails.getChoiceValue() > 0) {
                                    questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                } /*else {
                                  questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                                  }*/
                                questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                if (choiceDetails.isSkipToEnd() == true) {
                                    skipToEnd = true;
                                    submitted = true;
                                    lastPageSaved = question.getSurveyPageId();
                                } else {
                                    if (choiceDetails.getSkipToPageId() > 0) {
                                        SurveyPages pageDetails = surveyManager
                                                .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                        goToPage = pageDetails.getPageNum();
                                    }

                                    goToQuestion = choiceDetails.getSkipToQuestionId();

                                    lastQuestionSavedId = question.getId();
                                }

                                questionAnswer.setAnswerOther(question.getQuestionOtherValue());

                            } else {
                                questionAnswer.setAnswerText(question.getQuestionValue());
                                questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                            }

                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);
                        }
                    }
                }
            }
            if (!toRemove.isEmpty()) {
                questionAnswers.removeAll(toRemove);
            }

            if (questionFound == false) {

                if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                        && !"".equals(question.getQuestionValue())) {

                    if (question.getQuestionValue().contains(",")) {
                        String[] lineVector = question.getQuestionValue().split(",");

                        for (int i = 0; i < lineVector.length; i++) {
                            surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();
                            Integer qAnsValue = Integer.parseInt(lineVector[i]);

                            SurveyQuestionChoices choiceDetails = surveyManager
                                    .getSurveyQuestionChoice(qAnsValue);

                            if (choiceDetails.getChoiceValue() > 0) {
                                questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                            } /*else {
                              questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                              }*/
                            questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                            if (choiceDetails.isSkipToEnd() == true) {
                                skipToEnd = true;
                                submitted = true;
                                lastPageSaved = question.getSurveyPageId();
                            } else {
                                if (choiceDetails.getSkipToPageId() > 0) {
                                    SurveyPages pageDetails = surveyManager
                                            .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                    goToPage = pageDetails.getPageNum();
                                }

                                goToQuestion = choiceDetails.getSkipToQuestionId();

                                lastQuestionSavedId = question.getId();
                            }

                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);

                            questionAnswers.add(questionAnswer);

                            if (i == 0) {
                                questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                            }
                        }

                    } else {

                        surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                        boolean isInt = true;

                        try {
                            Integer.parseInt(question.getQuestionValue());
                        } catch (NumberFormatException e) {
                            isInt = false;
                        } catch (NullPointerException e) {
                            isInt = false;
                        }

                        if (isInt) {
                            SurveyQuestionChoices choiceDetails = surveyManager
                                    .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));
                            if (choiceDetails.getChoiceValue() > 0) {
                                questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                            } /*else {
                              questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                              }*/
                            questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                            if (choiceDetails.isSkipToEnd() == true) {
                                skipToEnd = true;
                                submitted = true;
                                lastPageSaved = question.getSurveyPageId();
                            } else {
                                if (choiceDetails.getSkipToPageId() > 0) {
                                    SurveyPages pageDetails = surveyManager
                                            .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                    goToPage = pageDetails.getPageNum();
                                }

                                goToQuestion = choiceDetails.getSkipToQuestionId();

                                lastQuestionSavedId = question.getId();
                            }

                        } else {
                            questionAnswer.setAnswerText(question.getQuestionValue());
                        }

                        questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                        questionAnswer.setQuestionId(question.getId());
                        questionAnswer.setProgramPatientId(survey.getClientId());
                        questionAnswer.setProgramEngagementId(survey.getEngagementId());
                        questionAnswer.setqNum(question.getQuestionNum());
                        questionAnswer.setSurveyPageId(question.getSurveyPageId());
                        questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                        questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                        questionAnswer.setSaveToDB(true);
                        questionAnswer.setPageNum(currPageNum);

                        questionAnswers.add(questionAnswer);
                    }

                } else {
                    surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                    questionAnswer.setAnswerText(question.getQuestionValue());

                    questionAnswer.setQuestionId(question.getId());
                    questionAnswer.setProgramPatientId(survey.getClientId());
                    questionAnswer.setProgramEngagementId(survey.getEngagementId());
                    questionAnswer.setqNum(question.getQuestionNum());
                    questionAnswer.setSurveyPageId(question.getSurveyPageId());
                    questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                    questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                    questionAnswer.setSaveToDB(true);
                    questionAnswer.setPageNum(currPageNum);

                    questionAnswers.add(questionAnswer);
                }

            }

            lastQuestionSaved = question.getQuestionNum();
        }

        /* Remove questions passed the last question answered */
        List<surveyQuestionAnswers> updatedquestionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Iterator<surveyQuestionAnswers> itr = updatedquestionAnswers.iterator();

        while (itr.hasNext()) {
            surveyQuestionAnswers questionAnswer = itr.next();

            if (questionAnswer.getqNum() > lastQuestionSaved) {
                itr.remove();
            }
        }

    }

    survey NextPage = new survey();
    NextPage.setClientId(survey.getClientId());
    NextPage.setSurveyId(survey.getSurveyId());
    NextPage.setSurveyTitle(survey.getSurveyTitle());
    NextPage.setPrevButton(survey.getPrevButton());
    NextPage.setNextButton(survey.getNextButton());
    NextPage.setSaveButton(survey.getSaveButton());
    NextPage.setSubmittedSurveyId(survey.getSubmittedSurveyId());
    NextPage.setEntityIds(survey.getEntityIds());

    SurveyPages currentPage = null;
    Integer qNum = 1;
    Integer nextPage = 1;

    /* Get the pages */
    List<SurveyPages> surveyPages = surveyManager.getSurveyPages(survey.getSurveyId(), false, 0, 0, 0);

    if ("prev".equals(action)) {
        mav.setViewName("/takeSurvey");

        currPageNum--;
        mav.addObject("currPageNum", currPageNum);

        List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");

        nextPage = seenPages.get(seenPages.size() - 1);
        /* Remove this page from array */
        seenPages.remove(seenPages.size() - 1);

        currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId);

        Integer totalPageQuestions = 0;

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
            question.setQuestionValue("");
            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {
                        if ("".equals(question.getQuestionValue())) {
                            question.setQuestionValue(questionAnswer.getAnswerText());
                            if (!"".equals(questionAnswer.getAnswerOther())) {
                                question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                            }
                        } else {
                            String currValue = question.getQuestionValue();
                            currValue += ",";
                            currValue += questionAnswer.getAnswerText();
                            question.setQuestionValue(currValue);
                        }
                    }
                }
            }

            if (question.getAnswerTypeId() != 7) {
                totalPageQuestions += 1;
            }
        }

        qNum = (survey.getLastQNumAnswered() - totalPageQuestions) - 1;
    } else if ("next".equals(action)) {
        mav.setViewName("/takeSurvey");

        currPageNum++;
        mav.addObject("currPageNum", currPageNum);

        if (goToPage > 0) {
            nextPage = goToPage;
        } else {

            /* Check to see if page has any skip logic */
            SurveyPages currentPageDetails = surveyManager.getSurveyPageDetails(survey.getPageId());
            if (currentPageDetails.getSkipToPage() > 0) {
                SurveyPages skiptoPageDetails = surveyManager
                        .getSurveyPageDetails(currentPageDetails.getSkipToPage());
                nextPage = skiptoPageDetails.getPageNum();
            } else if (currentPageDetails.getSkipToPage() == -1) {
                skipToEnd = true;
                submitted = true;
            } else {
                nextPage = survey.getCurrentPage() + 1;
            }
        }

        List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");
        seenPages.add(survey.getCurrentPage());

        currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId);

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
            String currDBValue = question.getQuestionValue();
            String currDBOtherValue = question.getQuestionOtherValue();
            question.setQuestionValue("");
            question.setQuestionOtherValue("");
            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {
                        if ("".equals(question.getQuestionValue())) {
                            question.setQuestionValue(questionAnswer.getAnswerText());
                            if (!"".equals(questionAnswer.getAnswerOther())) {
                                question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                            }
                        } else {
                            String currValue = question.getQuestionValue();
                            currValue += ",";
                            currValue += questionAnswer.getAnswerText();
                            question.setQuestionValue(currValue);
                        }
                    }
                }
            }

            if ("".equals(question.getQuestionValue())) {
                question.setQuestionValue(currDBValue);
                if ("".equals(question.getQuestionOtherValue())) {
                    question.setQuestionOtherValue(currDBOtherValue);
                }
            }
        }

        qNum = survey.getLastQNumAnswered();

    } else if ("save".equals(action)) {
        submitted = false;
    } else if ("done".equals(action)) {
        skipToEnd = true;
        submitted = true;
    }

    /**
     * If saving the survey, save and redirect to the survey list page *
     */
    if ("save".equals(action)) {
        User userDetails = (User) session.getAttribute("userDetails");

        /**
         * Submit answers to DB *
         */
        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                questionAnswers, submitted, selectedEntities);

        //if (surveyContentCriterias != null) {
        if (session.getAttribute("selectedContentCriterias") != null) {
            List<surveyContentCriteria> selectedContentCriteria = (List<surveyContentCriteria>) session
                    .getAttribute("selectedContentCriterias");

            Iterator<surveyContentCriteria> it = selectedContentCriteria.iterator();

            /* Delete existing code sets */
            surveyManager.deleteSurveyCodeSets(submittedSurveyId);

            while (it.hasNext()) {

                surveyContentCriteria criteria = it.next();

                if (criteria.isChecked()) {
                    submittedsurveycontentcriteria savedCodeSets = new submittedsurveycontentcriteria();
                    savedCodeSets.setCodeId(criteria.getCodeId());
                    savedCodeSets.setEntityId(criteria.getSchoolId());
                    savedCodeSets.setSubmittedSurveyId(submittedSurveyId);

                    surveyManager.submitSurveyCodeSets(savedCodeSets);
                }
            }
        }

        encryptObject encrypt = new encryptObject();
        Map<String, String> map;

        //Encrypt the use id to pass in the url
        map = new HashMap<String, String>();
        map.put("id", Integer.toString(survey.getSurveyId()));
        map.put("topSecret", topSecret);

        String[] encrypted = encrypt.encryptObject(map);

        mav = new ModelAndView(new RedirectView("/surveys?i=" + encrypted[0] + "&v=" + encrypted[1]));
    } /**
      * If reached the last page or an option was selected to skip to the end *
      */
    else if (currentPage == null || skipToEnd == true) {

        if (disabled == false) {
            User userDetails = (User) session.getAttribute("userDetails");

            /* If skipToEnd == true && submitted == true we need to remove any questions that 
            appear after the last saved page
            */
            if (skipToEnd == true && submitted == true && lastPageSaved > 0
                    && survey.getSubmittedSurveyId() > 0) {
                surveyManager.removeOldAnswers(survey.getSubmittedSurveyId(), lastPageSaved);
            }

            /**
             * Submit answers to DB *
             */
            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");
            Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                    questionAnswers, submitted, selectedEntities);

            if (session.getAttribute("selectedContentCriterias") != null) {
                List<surveyContentCriteria> selectedContentCriteria = (List<surveyContentCriteria>) session
                        .getAttribute("selectedContentCriterias");

                Iterator<surveyContentCriteria> it = selectedContentCriteria.iterator();

                /* Delete existing code sets */
                surveyManager.deleteSurveyCodeSets(submittedSurveyId);

                while (it.hasNext()) {

                    surveyContentCriteria criteria = it.next();

                    if (criteria.isChecked()) {
                        submittedsurveycontentcriteria savedCodeSets = new submittedsurveycontentcriteria();
                        savedCodeSets.setCodeId(criteria.getCodeId());
                        savedCodeSets.setEntityId(criteria.getSchoolId());
                        savedCodeSets.setSubmittedSurveyId(submittedSurveyId);

                        surveyManager.submitSurveyCodeSets(savedCodeSets);
                    }
                }
            }

            encryptObject encrypt = new encryptObject();
            Map<String, String> map1;
            Map<String, String> map2;

            //Encrypt the use id to pass in the url
            map1 = new HashMap<String, String>();
            map1.put("id", Integer.toString(survey.getSurveyId()));
            map1.put("topSecret", topSecret);

            //Encrypt the use id to pass in the url
            map2 = new HashMap<String, String>();
            map2.put("id", Integer.toString(submittedSurveyId));
            map2.put("topSecret", topSecret);

            String[] encrypted = encrypt.encryptObject(map1);
            String[] encrypted2 = encrypt.encryptObject(map2);

            /** Check to see if this program has access to the document module **/
            boolean hasDocumentModule = false;
            String[][] availablePrograms = (String[][]) session.getAttribute("availModules");

            for (int p = 0; p < availablePrograms.length; p++) {
                if (Integer.parseInt(availablePrograms[p][3]) == 10) {
                    hasDocumentModule = true;
                }
            }

            mav.addObject("hasDocumentModule", hasDocumentModule);

            mav.setViewName("/completedSurvey");
            surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());
            mav.addObject("surveyDetails", surveyDetails);

            List<county> countyList = (List<county>) session.getAttribute("countyList");
            mav.addObject("selCounties", countyList);
            mav.addObject("surveys", surveys);
            mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));
            mav.addObject("i", encrypted[0]);
            mav.addObject("v", encrypted[1]);
            mav.addObject("i2", encrypted2[0]);
            mav.addObject("v2", encrypted2[1]);
            mav.addObject("submittedSurveyId", submittedSurveyId);

            /* Get a list of survey documents */
            List<submittedSurveyDocuments> surveyDocuments = surveyManager
                    .getSubmittedSurveyDocuments(submittedSurveyId);

            if (surveyDocuments != null && surveyDocuments.size() > 0) {
                for (submittedSurveyDocuments document : surveyDocuments) {
                    if (document.getUploadedFile() != null && !"".equals(document.getUploadedFile())) {
                        int index = document.getUploadedFile().lastIndexOf('.');
                        document.setFileExt(document.getUploadedFile().substring(index + 1));

                        if (document.getUploadedFile().length() > 60) {
                            String shortenedTitle = document.getUploadedFile().substring(0, 30) + "..."
                                    + document.getUploadedFile().substring(
                                            document.getUploadedFile().length() - 10,
                                            document.getUploadedFile().length());
                            document.setShortenedTitle(shortenedTitle);
                        }
                        document.setEncodedTitle(URLEncoder.encode(document.getUploadedFile(), "UTF-8"));

                    }
                }
            }

            mav.addObject("surveyDocuments", surveyDocuments);

        } else {

        }

    } else {
        NextPage.setPageTitle(currentPage.getPageTitle());
        NextPage.setPageDesc(currentPage.getPageDesc());
        NextPage.setSurveyPageQuestions(currentPage.getSurveyQuestions());
        NextPage.setPageId(currentPage.getId());

        /* Loop through to get actually question answers */

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {

            String questionValue = "";

            while (it.hasNext()) {
                surveyQuestionAnswers questionAnswer = it.next();

                if (questionAnswer.getQuestionId() == question.getId()) {

                    if (questionAnswer != null) {
                        if (questionAnswer.getAnswerId() > 0) {
                            questionValue += String.valueOf(questionAnswer.getAnswerId());
                        } else {
                            questionValue += questionAnswer.getAnswerText();
                        }

                        questionValue += ",";
                    }
                }
            }

            if (!"".equals(questionValue)) {
                question.setQuestionValue(StringEscapeUtils.escapeHtml3(questionValue.replaceAll("(,)*$", "")));
            }
        }

        NextPage.setTotalPages(surveyPages.size());
        NextPage.setCurrentPage(nextPage);
        NextPage.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

        mav.addObject("survey", NextPage);
        mav.addObject("surveyPages", surveyPages);
        mav.addObject("qNum", qNum);
        mav.addObject("selectedEntities", selectedEntities);
        List<county> countyList = (List<county>) session.getAttribute("countyList");
        mav.addObject("selCounties", countyList);
        mav.addObject("surveys", surveys);
        mav.addObject("disabled", disabled);
        mav.addObject("selSurvey", survey.getSurveyId());
    }

    return mav;
}

From source file:com.rr.wabshs.ui.surveys.surveyController.java

/**
 * The '/takeSurvey' POST request will submit the survey page.
 *
 * @param survey/*from   w w  w.  j av  a2s .c o m*/
 * @param session
 * @param redirectAttr
 * @param action
 * @param goToPage
 * @param disabled
 * @param entityIds
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/submitSurvey", method = RequestMethod.POST)
public ModelAndView saveSurveyPage(@ModelAttribute(value = "survey") survey survey, HttpSession session,
        RedirectAttributes redirectAttr, @RequestParam String action, @RequestParam Integer goToPage,
        @RequestParam(value = "entityIds", required = false) List<String> entityIds,
        @RequestParam(value = "selectedEntities", required = false) List<String> selectedEntities,
        @RequestParam(value = "disabled", required = true, defaultValue = "false") boolean disabled,
        @RequestParam(value = "currPageNum", required = true) int currPageNum,
        @RequestParam(value = "showPrograms", required = false) boolean showPrograms,
        @RequestParam(value = "SurveyURL", required = true) String SurveyURL) throws Exception {

    Integer goToQuestion = 0;
    boolean skipToEnd = false;
    boolean submitted = false;

    ModelAndView mav = new ModelAndView();
    mav.addObject("showPrograms", showPrograms);
    mav.addObject("surveyURL", SurveyURL);

    List<Integer> entityIdList = null;
    if (entityIds != null && !"".equals(entityIds) && !entityIds.isEmpty()) {
        entityIdList = new ArrayList<Integer>();

        for (String entityId : entityIds) {
            Integer entityIdasInt = Integer.parseInt(entityId);

            entityIdList.add(entityIdasInt);
        }
        survey.setEntityIds(entityIdList);
    }

    Integer lastQuestionSavedId = 0;
    Integer lastPageSaved = 0;

    if ("next".equals(action) || "done".equals(action) || "save".equals(action)) {
        goToPage = 0;
        Integer lastQuestionSaved = 0;
        List<SurveyQuestions> questions = survey.getSurveyPageQuestions();

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : questions) {

            boolean questionFound = false;

            List<surveyQuestionAnswers> toRemove = new ArrayList<surveyQuestionAnswers>();

            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if ((questionAnswer.getPageNum() > currPageNum)) {
                        questionAnswer.setSaveToDB(false);
                    }

                    if (questionAnswer.getQuestionId() == question.getId()) {

                        if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                                && question.getQuestionValue().contains(",")) {
                            toRemove.add(questionAnswer);
                        } else {
                            questionFound = true;

                            boolean isInteger = isQuestionValueNumeric(question.getQuestionValue());

                            if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                                    && isInteger == true) {
                                SurveyQuestionChoices choiceDetails = surveyManager
                                        .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));

                                if (choiceDetails == null) {
                                    questionAnswer.setAnswerText(question.getQuestionValue());
                                } else {
                                    if (choiceDetails.getChoiceValue() > 0) {
                                        questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                    } /*else {
                                      questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                                      }*/
                                    questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                    if (choiceDetails.isSkipToEnd() == true) {
                                        skipToEnd = true;
                                        submitted = true;
                                        lastPageSaved = question.getSurveyPageId();
                                    } else {
                                        if (choiceDetails.getSkipToPageId() > 0) {
                                            SurveyPages pageDetails = surveyManager
                                                    .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                            goToPage = pageDetails.getPageNum();
                                        }

                                        goToQuestion = choiceDetails.getSkipToQuestionId();

                                        lastQuestionSavedId = question.getId();
                                    }

                                    questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                                }

                            } else {
                                questionAnswer.setAnswerText(question.getQuestionValue());
                            }

                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);
                        }
                    }
                }
            }
            if (!toRemove.isEmpty()) {
                questionAnswers.removeAll(toRemove);
            }

            if (questionFound == false) {

                if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                        && !"".equals(question.getQuestionValue())) {
                    if (question.getQuestionValue().contains(",")) {
                        String[] lineVector = question.getQuestionValue().split(",");
                        boolean answerAdded = true;
                        for (int i = 0; i < lineVector.length; i++) {
                            surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                            boolean isInteger = isQuestionValueNumeric(lineVector[i]);

                            if (isInteger) {
                                Integer qAnsValue = Integer.parseInt(lineVector[i]);

                                SurveyQuestionChoices choiceDetails = surveyManager
                                        .getSurveyQuestionChoice(qAnsValue);

                                if (choiceDetails == null) {
                                    answerAdded = false;
                                    break;
                                }

                                if (choiceDetails.getChoiceValue() > 0) {
                                    questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                } /*else {
                                  questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                                  }*/
                                questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                if (choiceDetails.isSkipToEnd() == true) {
                                    skipToEnd = true;
                                    submitted = true;
                                    lastPageSaved = question.getSurveyPageId();
                                } else {
                                    if (choiceDetails.getSkipToPageId() > 0) {
                                        SurveyPages pageDetails = surveyManager
                                                .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                        goToPage = pageDetails.getPageNum();
                                    }

                                    goToQuestion = choiceDetails.getSkipToQuestionId();

                                    lastQuestionSavedId = question.getId();
                                }
                                questionAnswer.setQuestionId(question.getId());
                                questionAnswer.setProgramPatientId(survey.getClientId());
                                questionAnswer.setProgramEngagementId(survey.getEngagementId());
                                questionAnswer.setqNum(question.getQuestionNum());
                                questionAnswer.setSurveyPageId(question.getSurveyPageId());
                                questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                                questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                                questionAnswer.setSaveToDB(true);
                                questionAnswer.setPageNum(currPageNum);

                                questionAnswers.add(questionAnswer);

                                if (i == 0) {
                                    questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                                }
                            } else {
                                answerAdded = false;
                                break;
                            }
                        }

                        if (!answerAdded) {
                            surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                            questionAnswer.setAnswerText(question.getQuestionValue());

                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);

                            questionAnswers.add(questionAnswer);
                        }

                    } else {

                        surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                        boolean isInteger = isQuestionValueNumeric(question.getQuestionValue());

                        if (isInteger) {
                            SurveyQuestionChoices choiceDetails = surveyManager
                                    .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));

                            if (choiceDetails != null) {
                                if (choiceDetails.getChoiceValue() > 0) {
                                    questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                }
                                questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                if (choiceDetails.isSkipToEnd() == true) {
                                    skipToEnd = true;
                                    submitted = true;
                                    lastPageSaved = question.getSurveyPageId();
                                } else {
                                    if (choiceDetails.getSkipToPageId() > 0) {
                                        SurveyPages pageDetails = surveyManager
                                                .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                        goToPage = pageDetails.getPageNum();
                                    }

                                    goToQuestion = choiceDetails.getSkipToQuestionId();

                                    lastQuestionSavedId = question.getId();
                                }
                            } else {
                                questionAnswer.setAnswerText(question.getQuestionValue());
                            }

                        } else {
                            questionAnswer.setAnswerText(question.getQuestionValue());
                        }

                        questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                        questionAnswer.setQuestionId(question.getId());
                        questionAnswer.setProgramPatientId(survey.getClientId());
                        questionAnswer.setProgramEngagementId(survey.getEngagementId());
                        questionAnswer.setqNum(question.getQuestionNum());
                        questionAnswer.setSurveyPageId(question.getSurveyPageId());
                        questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                        questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                        questionAnswer.setSaveToDB(true);
                        questionAnswer.setPageNum(currPageNum);

                        questionAnswers.add(questionAnswer);
                    }

                } else {
                    surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                    questionAnswer.setAnswerText(question.getQuestionValue());

                    questionAnswer.setQuestionId(question.getId());
                    questionAnswer.setProgramPatientId(survey.getClientId());
                    questionAnswer.setProgramEngagementId(survey.getEngagementId());
                    questionAnswer.setqNum(question.getQuestionNum());
                    questionAnswer.setSurveyPageId(question.getSurveyPageId());
                    questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                    questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                    questionAnswer.setSaveToDB(true);
                    questionAnswer.setPageNum(currPageNum);

                    questionAnswers.add(questionAnswer);
                }

            }

            lastQuestionSaved = question.getQuestionNum();
        }

        /* Remove questions passed the last question answered */
        List<surveyQuestionAnswers> updatedquestionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Iterator<surveyQuestionAnswers> itr = updatedquestionAnswers.iterator();

        while (itr.hasNext()) {
            surveyQuestionAnswers questionAnswer = itr.next();

            if (questionAnswer.getqNum() > lastQuestionSaved) {
                itr.remove();
            }
        }

    }

    survey NextPage = new survey();
    NextPage.setClientId(survey.getClientId());
    NextPage.setSurveyId(survey.getSurveyId());
    NextPage.setSurveyTitle(survey.getSurveyTitle());
    NextPage.setPrevButton(survey.getPrevButton());
    NextPage.setNextButton(survey.getNextButton());
    NextPage.setSaveButton(survey.getSaveButton());
    NextPage.setSubmittedSurveyId(survey.getSubmittedSurveyId());
    NextPage.setEntityIds(survey.getEntityIds());

    SurveyPages currentPage = null;
    Integer qNum = 1;
    Integer nextPage = 1;

    /* Get the pages */
    Integer selEntityId = 0;
    if (entityIdList != null) {
        if (entityIdList.size() > 0) {
            selEntityId = entityIdList.get(0);
        }
    }
    List<SurveyPages> surveyPages = surveyManager.getSurveyPages(survey.getSurveyId(), false, 0, 0, 0,
            selEntityId);

    if ("prev".equals(action)) {
        mav.setViewName("/takeSurvey");

        currPageNum--;
        mav.addObject("currPageNum", currPageNum);

        List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");

        nextPage = seenPages.get(seenPages.size() - 1);
        /* Remove this page from array */
        seenPages.remove(seenPages.size() - 1);

        currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId, selEntityId);

        Integer totalPageQuestions = 0;

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
            question.setQuestionValue("");
            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {
                        if (question.getMultipleFieldsFromTable() != null
                                && question.getMultipleFieldsFromTable().size() > 0) {
                            if (questionAnswer.getAnswerText().contains(",")) {
                                List<String> multiFieldValue = Arrays
                                        .asList(questionAnswer.getAnswerText().split(","));

                                for (multipleFieldsFromTable multipleField : question
                                        .getMultipleFieldsFromTable()) {
                                    if (multiFieldValue != null && multiFieldValue.size() > 0) {
                                        for (int i = 0; i < multiFieldValue.size(); i++) {
                                            if (multiFieldValue.get(i).contains("-")) {
                                                List<String> value = Arrays
                                                        .asList(multiFieldValue.get(i).split("-"));
                                                if (multipleField.getDisplayId() == Integer
                                                        .parseInt(value.get(0))) {
                                                    multipleField.setDisplayValue(value.get(1));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else if ("".equals(question.getQuestionValue())) {
                            question.setQuestionValue(questionAnswer.getAnswerText());
                            if (!"".equals(questionAnswer.getAnswerOther())) {
                                question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                            }
                        } else {
                            String currValue = question.getQuestionValue();
                            currValue += ",";
                            currValue += questionAnswer.getAnswerText();
                            question.setQuestionValue(currValue);
                        }
                    }
                }
            }

            if (question.getAnswerTypeId() != 7) {
                totalPageQuestions += 1;
            }
        }

        surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());
        mav.addObject("surveyTag", surveyDetails.getSurveyTag());

        qNum = (survey.getLastQNumAnswered() - totalPageQuestions) - 1;
    } else if ("next".equals(action)) {
        mav.setViewName("/takeSurvey");

        currPageNum++;
        mav.addObject("currPageNum", currPageNum);

        if (goToPage > 0) {
            nextPage = goToPage;
        } else {

            /* Check to see if page has any skip logic */
            SurveyPages currentPageDetails = surveyManager.getSurveyPageDetails(survey.getPageId());
            if (currentPageDetails.getSkipToPage() > 0) {
                SurveyPages skiptoPageDetails = surveyManager
                        .getSurveyPageDetails(currentPageDetails.getSkipToPage());
                nextPage = skiptoPageDetails.getPageNum();
            } else if (currentPageDetails.getSkipToPage() == -1) {
                skipToEnd = true;
                submitted = true;
            } else {
                nextPage = survey.getCurrentPage() + 1;
            }
        }

        List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");
        seenPages.add(survey.getCurrentPage());

        currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId, selEntityId);

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
            String currDBValue = question.getQuestionValue();
            String currDBOtherValue = question.getQuestionOtherValue();
            question.setQuestionValue("");
            question.setQuestionOtherValue("");
            if (questionAnswers != null && questionAnswers.size() > 0) {

                Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {
                        if ("".equals(question.getQuestionValue())) {
                            question.setQuestionValue(questionAnswer.getAnswerText());
                            if (!"".equals(questionAnswer.getAnswerOther())) {
                                question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                            }
                        } else {
                            String currValue = question.getQuestionValue();
                            currValue += ",";
                            currValue += questionAnswer.getAnswerText();
                            question.setQuestionValue(currValue);
                        }
                    }
                }
            }

            if ("".equals(question.getQuestionValue())) {
                question.setQuestionValue(currDBValue);
                if (!"".equals(question.getQuestionOtherValue())) {
                    question.setQuestionOtherValue(currDBOtherValue);
                }
            }
        }

        qNum = survey.getLastQNumAnswered();

        surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());
        mav.addObject("surveyTag", surveyDetails.getSurveyTag());

    } else if ("save".equals(action)) {
        submitted = false;
    } else if ("done".equals(action)) {
        skipToEnd = true;
        submitted = true;
    }

    /**
     * If saving the survey, save and redirect to the survey list page *
     */
    if ("save".equals(action)) {
        User userDetails = (User) session.getAttribute("userDetails");

        /**
         * Submit answers to DB *
         */
        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                questionAnswers, submitted, selectedEntities);

        if (session.getAttribute("selectedProgramProfiles") != null) {
            List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                    .getAttribute("selectedProgramProfiles");

            Iterator<surveyProgramProfiles> it = selectedProgramProfile.iterator();

            /* Delete existing code sets */
            surveyManager.deleteSurveyPrograms(submittedSurveyId);

            while (it.hasNext()) {

                surveyProgramProfiles criteria = it.next();

                if (criteria.isChecked()) {
                    submittedsurveyprogramprofiles savedProgramProfile = new submittedsurveyprogramprofiles();
                    savedProgramProfile.setProgramProfileId(criteria.getProgramProfileId());
                    savedProgramProfile.setEntityId(criteria.getEntityId());
                    savedProgramProfile.setSubmittedSurveyId(submittedSurveyId);

                    surveyManager.submitSurveyPrograms(savedProgramProfile);
                }
            }
        }

        if (session.getAttribute("selectedExtras") != null) {
            List<surveyExtraInformation> selectedExtraInformation = (List<surveyExtraInformation>) session
                    .getAttribute("selectedExtras");

            Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

            /* Delete existing code sets */
            surveyManager.deleteSurveyCoordinators(submittedSurveyId);

            while (it.hasNext()) {

                surveyExtraInformation criteria = it.next();

                if (criteria.isChecked()) {
                    submittedsurveycoordinators savedCoordinator = new submittedsurveycoordinators();
                    savedCoordinator.setPartnerProfileId(criteria.getExtraId());
                    savedCoordinator.setEntityId(criteria.getEntityId());
                    savedCoordinator.setSubmittedSurveyId(submittedSurveyId);

                    surveyManager.submitSurveyCoordinators(savedCoordinator);
                }
            }
        }

        encryptObject encrypt = new encryptObject();
        Map<String, String> map;

        //Encrypt the use id to pass in the url
        map = new HashMap<String, String>();
        map.put("id", Integer.toString(survey.getSurveyId()));
        map.put("topSecret", topSecret);

        String[] encrypted = encrypt.encryptObject(map);

        mav = new ModelAndView(new RedirectView("/surveys?i=" + encrypted[0] + "&v=" + encrypted[1]));
    } /**
      * If reached the last page or an option was selected to skip to the end *
      */
    else if (currentPage == null || skipToEnd == true) {

        if (disabled == false) {
            User userDetails = (User) session.getAttribute("userDetails");

            /* If skipToEnd == true && submitted == true we need to remove any questions that 
            appear after the last saved page
            */
            if (skipToEnd == true && submitted == true && lastPageSaved > 0
                    && survey.getSubmittedSurveyId() > 0) {
                surveyManager.removeOldAnswers(survey.getSubmittedSurveyId(), lastPageSaved);
            }

            /**
             * Submit answers to DB *
             */
            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");
            Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                    questionAnswers, submitted, selectedEntities);

            if (session.getAttribute("selectedProgramProfiles") != null) {
                List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                        .getAttribute("selectedProgramProfiles");

                Iterator<surveyProgramProfiles> it = selectedProgramProfile.iterator();

                /* Delete existing code sets */
                surveyManager.deleteSurveyPrograms(submittedSurveyId);

                while (it.hasNext()) {

                    surveyProgramProfiles criteria = it.next();

                    if (criteria.isChecked()) {
                        submittedsurveyprogramprofiles savedProgramProfile = new submittedsurveyprogramprofiles();

                        savedProgramProfile.setProgramProfileId(criteria.getProgramProfileId());
                        savedProgramProfile.setEntityId(criteria.getEntityId());
                        savedProgramProfile.setSubmittedSurveyId(submittedSurveyId);

                        surveyManager.submitSurveyPrograms(savedProgramProfile);
                    }
                }
            }

            if (session.getAttribute("selectedExtras") != null) {
                List<surveyExtraInformation> selectedExtraInformation = (List<surveyExtraInformation>) session
                        .getAttribute("selectedExtras");

                Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

                /* Delete existing code sets */
                surveyManager.deleteSurveyCoordinators(submittedSurveyId);

                while (it.hasNext()) {

                    surveyExtraInformation criteria = it.next();

                    if (criteria.isChecked()) {
                        submittedsurveycoordinators savedCoordinator = new submittedsurveycoordinators();
                        savedCoordinator.setPartnerProfileId(criteria.getExtraId());
                        savedCoordinator.setEntityId(criteria.getEntityId());
                        savedCoordinator.setSubmittedSurveyId(submittedSurveyId);

                        surveyManager.submitSurveyCoordinators(savedCoordinator);
                    }
                }
            }

            encryptObject encrypt = new encryptObject();
            Map<String, String> map1;
            Map<String, String> map2;

            //Encrypt the use id to pass in the url
            map1 = new HashMap<String, String>();
            map1.put("id", Integer.toString(survey.getSurveyId()));
            map1.put("topSecret", topSecret);

            //Encrypt the use id to pass in the url
            map2 = new HashMap<String, String>();
            map2.put("id", Integer.toString(submittedSurveyId));
            map2.put("topSecret", topSecret);

            String[] encrypted = encrypt.encryptObject(map1);
            String[] encrypted2 = encrypt.encryptObject(map2);

            /** Check to see if this program has access to the document && client module **/
            boolean hasDocumentModule = false;
            boolean hasClientModule = false;
            String[][] availablePrograms = (String[][]) session.getAttribute("availModules");

            for (int p = 0; p < availablePrograms.length; p++) {
                if (Integer.parseInt(availablePrograms[p][3]) == 10) {
                    hasDocumentModule = true;
                }
                if (Integer.parseInt(availablePrograms[p][3]) == 1) {
                    hasClientModule = true;
                }
            }

            mav.addObject("hasDocumentModule", hasDocumentModule);
            mav.addObject("hasClientModule", hasClientModule);

            /* Find out if activity log needs to be tracked at the client level */
            List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                    .getAttribute("selectedProgramProfiles");
            surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());

            if (showPrograms && selectedProgramProfile != null && selectedProgramProfile.size() > 0) {
                if ("ActivityReporting".equals(surveyDetails.getSurveyTag())) {
                    mav.addObject("trackIndividuals", true);
                    mav.addObject("programProfileId", selectedProgramProfile.get(0).getProgramProfileId());
                }
            }

            mav.setViewName("/completedSurvey");
            mav.addObject("surveyDetails", surveyDetails);

            List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                    .getAttribute("secondTierEntities");
            mav.addObject("seltier2EntityList", tier2EntityList);
            mav.addObject("surveys", surveys);
            mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));

            mav.addObject("i", encrypted[0]);
            mav.addObject("v", encrypted[1]);
            mav.addObject("i2", encrypted2[0]);
            mav.addObject("v2", encrypted2[1]);

            mav.addObject("submittedSurveyId", submittedSurveyId);

            /* Get a list of survey documents */
            List<submittedSurveyDocuments> surveyDocuments = surveyManager
                    .getSubmittedSurveyDocuments(submittedSurveyId);

            if (surveyDocuments != null && surveyDocuments.size() > 0) {
                for (submittedSurveyDocuments document : surveyDocuments) {
                    if (document.getUploadedFile() != null && !"".equals(document.getUploadedFile())) {
                        int index = document.getUploadedFile().lastIndexOf('.');
                        document.setFileExt(document.getUploadedFile().substring(index + 1));

                        if (document.getUploadedFile().length() > 60) {
                            String shortenedTitle = document.getUploadedFile().substring(0, 30) + "..."
                                    + document.getUploadedFile().substring(
                                            document.getUploadedFile().length() - 10,
                                            document.getUploadedFile().length());
                            document.setShortenedTitle(shortenedTitle);
                        }
                        document.setEncodedTitle(URLEncoder.encode(document.getUploadedFile(), "UTF-8"));

                    }
                }
            }

            mav.addObject("surveyDocuments", surveyDocuments);

            /* Check to see if this survey is tied to a participant and session */
            if (survey.getClientId() > 0 && survey.getSessionId() > 0) {
                submittedsurveyforsessionparticipant surveySessionParticipantEntry = new submittedsurveyforsessionparticipant();
                surveySessionParticipantEntry.setSubmittedSurveyId(submittedSurveyId);
                surveySessionParticipantEntry.setParticipantId(survey.getClientId());
                surveySessionParticipantEntry.setSessionId(survey.getSessionId());
                surveySessionParticipantEntry.setSystemUserId(userDetails.getId());

                surveyManager.saveSurveyForSessionParticipant(surveySessionParticipantEntry);

                mav.addObject("participantSessionSurvey", true);
            } else if (survey.getSessionId() > 0) {
                mav.addObject("participantSessionSurvey", true);
            }

        } else {

        }

    } else {

        NextPage.setPageTitle(currentPage.getPageTitle());
        NextPage.setSurveyPageQuestions(currentPage.getSurveyQuestions());
        NextPage.setPageId(currentPage.getId());

        /* Loop through to get actually question answers */

        List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                .getAttribute("questionAnswers");
        Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

        for (SurveyQuestions question : currentPage.getSurveyQuestions()) {

            String questionValue = "";

            while (it.hasNext()) {
                surveyQuestionAnswers questionAnswer = it.next();

                if (questionAnswer.getQuestionId() == question.getId()) {

                    if (questionAnswer != null) {
                        if (questionAnswer.getAnswerId() > 0) {
                            questionValue += String.valueOf(questionAnswer.getAnswerId());
                        } else {
                            questionValue += questionAnswer.getAnswerText();
                        }

                        questionValue += ",";
                    }
                }
            }

            if (!"".equals(questionValue)) {
                question.setQuestionValue(StringEscapeUtils.escapeHtml3(questionValue.replaceAll("(,)*$", "")));
            }
        }

        NextPage.setTotalPages(surveyPages.size());
        NextPage.setCurrentPage(nextPage);
        NextPage.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

        mav.addObject("survey", NextPage);
        mav.addObject("surveyPages", surveyPages);
        mav.addObject("selectedEntities", selectedEntities);
        List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                .getAttribute("secondTierEntities");
        mav.addObject("seltier2EntityList", tier2EntityList);
        mav.addObject("qNum", qNum);
        mav.addObject("surveys", surveys);
        mav.addObject("disabled", disabled);
        mav.addObject("selSurvey", survey.getSurveyId());
    }

    return mav;
}

From source file:net.team2xh.crt.gui.entities.EntityTree.java

public void loadScene(Scene scene) {
    // Entities//from   w  w  w. j av  a  2s  .c om
    List<Node> entities = new LinkedList<>();
    for (Entity e : scene.getEntities()) {
        try {
            // TODO: Some way of differentiating similar objects in a scene
            // Counter ? maybe keep track of named variables
            entities.add(new DynamicNode(e) {
                @Override
                public String getHtmlDisplayName() {
                    return getDisplayName() + " <font color='!controlShadow'><i>"
                            + StringEscapeUtils.escapeHtml3(e.getCenter().toString()) + "</i></font>";
                }
            });
        } catch (IntrospectionException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    Children entitiesChildren = new Children.Array();
    entitiesChildren.add(entities.toArray(new Node[0]));
    for (Node n : entitiesChildren.getNodes()) {

    }
    Node entitiesNode = createNode(entitiesChildren, ICON_ENTITIES);
    entitiesNode.setDisplayName("Entities");
    entitiesNode.setShortDescription("The entities present in the compiled scene.");

    // Lights
    BeanContext lights = new BeanContextSupport();
    for (Light l : scene.getLights()) {
        lights.add(l);
    }
    Children lightsChildren = new BeanChildren(lights);
    Node lightsNode = createNode(lightsChildren, ICON_LIGHTS);
    lightsNode.setDisplayName("Lights");
    lightsNode.setShortDescription("The lights present in the compiled scene.");

    // Scene
    Children sceneChildren = new Children.Array();
    sceneChildren.add(new Node[] { lightsNode, entitiesNode });

    Node root = createNode(sceneChildren, ICON_SCENE);
    root.setDisplayName("Scene");
    root.setShortDescription("The current scene after execution of the script.");

    manager.setRootContext(root);

    SwingUtilities.invokeLater(() -> {
        tree.expandAll();
    });
}