<commit_before>/*
 * Copyright 2005-2013 The Kuali Foundation
 * 
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kra.questionnaire;

import static org.kuali.kra.infrastructure.Constants.MAPPING_BASIC;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.kuali.kra.bo.CoeusSubModule;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.printing.util.PrintingUtils;
import org.kuali.kra.proposaldevelopment.bo.AttachmentDataSource;
import org.kuali.kra.questionnaire.print.QuestionnairePrintingService;
import org.kuali.kra.questionnaire.question.Question;
import org.kuali.kra.service.VersioningService;
import org.kuali.kra.service.impl.VersioningServiceImpl;
import org.kuali.rice.kns.document.MaintenanceDocumentBase;
import org.kuali.rice.kns.web.struts.action.KualiMaintenanceDocumentAction;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.krad.exception.AuthorizationException;
import org.kuali.rice.krad.service.SequenceAccessorService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;

/*
 * Big issue is that questionnairequestions and usages can't be included in xmldoccontent because maintframework - questions &
 * usages are not defined in maint DD's 'maintsections'. Current work around is using KraMaintenanceDocument to make rice
 * maintenance framework to think that QnQuestions & QnUsages are defined in maintenance section. So, they will be saved in
 * xmldoccontent.
 * 
 * The hierarchical nature of data and heavily depending on js also needs some manipulation, so make these a little
 * complicated..
 */
/**
 * This is the maintenance action class is for questionnaire.
 */
public class QuestionnaireMaintenanceDocumentAction extends KualiMaintenanceDocumentAction {
    private static final Log LOG = LogFactory.getLog(QuestionnaireMaintenanceDocumentAction.class);
    private static final String PCP = "#;#";
    private static final String PQP = "#q#";
    private static final String PUP = "#u#";
    private static final String PFP = "#f#";
    private static final ActionForward RESPONSE_ALREADY_HANDLED = null;
    private static final String DOCUMENT_NUMBER = "documentNumber";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
        ActionForward forward = super.execute(mapping, qnForm, request, response);
        //check for deleted usages after the execute as execute is what populates the form inputs. Should be fine here as page is not
        //rendered until later. Check for same in save as should happen before save though.
        if (qnForm.getDocument() != null && ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject() != null) {
            Questionnaire newQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
                    .getNewMaintainableObject().getDataObject();
            removeDeletedUsages(newQuestionnaire);
        }
        return forward;
    }
    
    
    @Override
    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
        Questionnaire newQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
                .getNewMaintainableObject().getDataObject();
        removeDeletedUsages(newQuestionnaire);
        if (validateTemplateField(qnForm)) {
            if (newQuestionnaire.getSequenceNumber() == null) {
                newQuestionnaire.setSequenceNumber(1);
            }
            setupQuestionAndUsage(form);
            if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
                newQuestionnaire.setFileName(qnForm.getTemplateFile().getFileName());
                newQuestionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
            }
            qnForm.setNewQuestionnaireUsage(new QuestionnaireUsage());
            newQuestionnaire.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
            ActionForward forward = super.save(mapping, form, request, response);
            
            checkAndSetAllQuestionsAreUpToDate(qnForm);
            return forward; 
        }
        return mapping.findForward(Constants.MAPPING_BASIC);

    }
    
    private boolean validateTemplateField(QuestionnaireMaintenanceForm qnForm) {
        System.err.println("validateTemplateField");
        boolean retVal = true;
        final String fieldName = "document.newMaintainableObject.businessObject.fileName";
        try {
            if (!StringUtils.isBlank(qnForm.getTemplateFile().getFileName()) && (qnForm.getTemplateFile().getFileData() == null || qnForm.getTemplateFile().getFileData().length <= 0)) {
                GlobalVariables.getMessageMap().putError(fieldName, KeyConstants.ERROR_QUESTIONNAIRE_FILENAME_INVALID);
                retVal = false;
            }
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block<commit_msg>KRACOEUS-6598: Fixing Questionnaire copy.<commit_after>/*
 * Copyright 2005-2013 The Kuali Foundation
 * 
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kra.questionnaire;

import static org.kuali.kra.infrastructure.Constants.MAPPING_BASIC;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.kuali.kra.bo.CoeusSubModule;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.printing.util.PrintingUtils;
import org.kuali.kra.proposaldevelopment.bo.AttachmentDataSource;
import org.kuali.kra.questionnaire.print.QuestionnairePrintingService;
import org.kuali.kra.questionnaire.question.Question;
import org.kuali.kra.service.VersioningService;
import org.kuali.kra.service.impl.VersioningServiceImpl;
import org.kuali.rice.kns.document.MaintenanceDocumentBase;
import org.kuali.rice.kns.web.struts.action.KualiMaintenanceDocumentAction;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.krad.exception.AuthorizationException;
import org.kuali.rice.krad.service.SequenceAccessorService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;

/*
 * Big issue is that questionnairequestions and usages can't be included in xmldoccontent because maintframework - questions &
 * usages are not defined in maint DD's 'maintsections'. Current work around is using KraMaintenanceDocument to make rice
 * maintenance framework to think that QnQuestions & QnUsages are defined in maintenance section. So, they will be saved in
 * xmldoccontent.
 * 
 * The hierarchical nature of data and heavily depending on js also needs some manipulation, so make these a little
 * complicated..
 */
/**
 * This is the maintenance action class is for questionnaire.
 */
public class QuestionnaireMaintenanceDocumentAction extends KualiMaintenanceDocumentAction {
    private static final Log LOG = LogFactory.getLog(QuestionnaireMaintenanceDocumentAction.class);
    private static final String PCP = "#;#";
    private static final String PQP = "#q#";
    private static final String PUP = "#u#";
    private static final String PFP = "#f#";
    private static final ActionForward RESPONSE_ALREADY_HANDLED = null;
    private static final String DOCUMENT_NUMBER = "documentNumber";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
        ActionForward forward = super.execute(mapping, qnForm, request, response);
        //check for deleted usages after the execute as execute is what populates the form inputs. Should be fine here as page is not
        //rendered until later. Check for same in save as should happen before save though.
        if (qnForm.getDocument() != null && ((MaintenanceDocumentBase) qnForm.getDocument()).getNewMaintainableObject() != null) {
            Questionnaire newQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
                    .getNewMaintainableObject().getDataObject();
            removeDeletedUsages(newQuestionnaire);
        }
        return forward;
    }
    
    
    @Override
    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        QuestionnaireMaintenanceForm qnForm = (QuestionnaireMaintenanceForm) form;
        Questionnaire newQuestionnaire = (Questionnaire) ((MaintenanceDocumentBase) qnForm.getDocument())
                .getNewMaintainableObject().getDataObject();
        removeDeletedUsages(newQuestionnaire);
        if (validateTemplateField(qnForm)) {
            if (newQuestionnaire.getSequenceNumber() == null) {
                newQuestionnaire.setSequenceNumber(1);
            }
            setupQuestionAndUsage(form);
            if (qnForm.getTemplateFile() != null && StringUtils.isNotBlank(qnForm.getTemplateFile().getFileName())) {
                newQuestionnaire.setFileName(qnForm.getTemplateFile().getFileName());
                newQuestionnaire.setTemplate(qnForm.getTemplateFile().getFileData());
            }
            qnForm.setNewQuestionnaireUsage(new QuestionnaireUsage());
            newQuestionnaire.setDocumentNumber(((MaintenanceDocumentBase) qnForm.getDocument()).getDocumentNumber());
            ActionForward forward = super.save(mapping, form, request, response);
            
            checkAndSetAllQuestionsAreUpToDate(qnForm);
            return forward; 
        }
        return mapping.findForward(Constants.MAPPING_BASIC);

    }
    
    private boolean validateTemplateField(QuestionnaireMaintenanceForm qnForm) {
        System.err.println("validateTemplateField");
        boolean retVal = true;
        final String fieldName = "document.newMaintainableObject.businessObject.fileName";
        try {
            if (ObjectUtils.isNotNull(qnForm.getTemplateFile()) && !StringUtils.isBlank(qnForm.getTemplateFile().getFileName()) && (qnForm.getTemplateFile().getFileData() == null || qnForm.getTemplateFile().getFileData().length <= 0)) {
                GlobalVariables.getMessageMap().putError(fieldName, KeyConstants.ERROR_QUESTIONNAIRE_FILENAME_INVALID);
                retVal = false;
            }
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
{'fraction_non_alphanumeric': 0.08703582111329977, 'fraction_numerical': 0.002188662727073758, 'mean_word_length': 4.028613352898019, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4944354', 'n_tokens_mistral': 3735, 'n_tokens_neox': 3626, 'n_words': 901}