/** * method to stream the byte array to response object * * @param fileContents * @param fileName * @param fileContentType * @param response * @throws Exception */ protected void streamToResponse( org.kuali.kra.proposaldevelopment.bo.AttachmentDataSource attachmentDataSource, HttpServletResponse response) throws Exception { byte[] xbts = attachmentDataSource.getContent(); ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(xbts.length); baos.write(xbts); WebUtils.saveMimeOutputStreamAsFile( response, attachmentDataSource.getContentType(), baos, attachmentDataSource.getFileName()); } finally { try { if (baos != null) { baos.close(); baos = null; } } catch (IOException ioEx) { LOG.error("Error while downloading attachment"); throw new RuntimeException("IOException occurred while downloading attachment", ioEx); } } }
/** * This method resets the Batch Correspondence history. This involves clearing the previous * displayed history information and collapsing all panel content with the exception of the Batch * Correspondence panel. * * @param committeeForm the CommitteeFormBase */ public void resetBatchCorrespondenceHistory(CommitteeFormBase committeeForm) { setBatchCorrespondenceHistory(null); committeeForm.setTabStates(new HashMap<String, String>()); committeeForm .getTabStates() .put(WebUtils.generateTabKey(BATCH_CORRESPONDENCE_PANEL_TITLE), "OPEN"); }
/** * Handy method to stream the byte array to response object * * @param attachmentDataSource * @param response * @throws Exception */ public void streamToResponse( AttachmentDataSource attachmentDataSource, HttpServletResponse response) throws Exception { byte[] xbts = attachmentDataSource.getContent(); ByteArrayOutputStream baos = null; if (xbts != null) try { baos = new ByteArrayOutputStream(xbts.length); baos.write(xbts); WebUtils.saveMimeOutputStreamAsFile( response, attachmentDataSource.getContentType(), baos, attachmentDataSource.getFileName()); } finally { try { if (baos != null) { baos.close(); baos = null; } } catch (IOException ioEx) { LOG.warn(ioEx.getMessage(), ioEx); } } }
/** @return the tab key for this hide/show block */ public String getTabKey() { if (tabKey == null) { tabKey = WebUtils.generateTabKey(renderingContext.getGroupLabel() + definition.getLabel()) + "-" + renderingContext .getAccountingLinePropertyPath() .replaceAll("\\.", "-") .replaceAll("\\[", "(") .replaceAll("\\]", ")"); } return tabKey; }
/** @see org.apache.struts.taglib.html.SelectTag#doEndTag() */ public int doEndTag() throws JspException { int returnVal = super.doEndTag(); if (!getDisabled() && !getReadonly()) { String name = prepareName(); if (StringUtils.isNotBlank(name)) { ActionForm form = WebUtils.getKualiForm(pageContext); if (form != null && form instanceof PojoForm) { ((PojoForm) form).registerEditableProperty(name); } } } return returnVal; }
private void downloadFile( ActionForm form, HttpServletRequest request, HttpServletResponse response, byte[] bytesToDownload, String fileName, String contentType) throws Exception { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(bytesToDownload.length); baos.write(bytesToDownload); WebUtils.saveMimeOutputStreamAsFile(response, contentType, baos, fileName); } finally { try { if (baos != null) { baos.close(); baos = null; } } catch (IOException ioEx) { LOG.warn(ioEx.getMessage(), ioEx); } } }
/** * Runs the reports or dump selected by the user using the BudgetConstructionDocumentReportMode to * help determine the various objects needed to actually build the report data and render the * report. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward performReportDump( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ReportRunnerForm reportRunnerForm = (ReportRunnerForm) form; String principalName = GlobalVariables.getUserSession().getPerson().getPrincipalId(); int selectIndex = this.getSelectedLine(request); String reportModeName = reportRunnerForm .getBudgetConstructionDocumentReportModes() .get(selectIndex) .getReportModeName(); Collection reportSet = new ArrayList(); String jasperFileName = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); switch (selectIndex) { case 0: { jasperFileName = "BudgetAccountObjectDetail"; SpringContext.getBean(BudgetConstructionDocumentAccountObjectDetailReportService.class) .updateDocumentAccountObjectDetailReportTable( principalName, reportRunnerForm.getDocumentNumber(), reportRunnerForm.getUniversityFiscalYear(), reportRunnerForm.getChartOfAccountsCode(), reportRunnerForm.getAccountNumber(), reportRunnerForm.getSubAccountNumber()); reportSet = SpringContext.getBean( BudgetConstructionDocumentAccountObjectDetailReportService.class) .buildReports(principalName); break; } case 1: { jasperFileName = "BudgetAccountSalaryDetail"; reportSet = SpringContext.getBean(BudgetConstructionAccountSalaryDetailReportService.class) .buildReports( reportRunnerForm.getUniversityFiscalYear(), reportRunnerForm.getChartOfAccountsCode(), reportRunnerForm.getAccountNumber(), reportRunnerForm.getSubAccountNumber()); break; } case 2: { jasperFileName = "BudgetAccountMonthlyDetail"; reportSet = SpringContext.getBean(BudgetConstructionAccountMonthlyDetailReportService.class) .buildReports( reportRunnerForm.getDocumentNumber(), reportRunnerForm.getUniversityFiscalYear(), reportRunnerForm.getChartOfAccountsCode(), reportRunnerForm.getAccountNumber(), reportRunnerForm.getSubAccountNumber()); break; } case 3: { return new ActionForward( buildReportExportForwardURL( reportRunnerForm, mapping, BudgetConstructionReportMode.ACCOUNT_EXPORT.reportModeName), true); } case 4: { return new ActionForward( buildReportExportForwardURL( reportRunnerForm, mapping, BudgetConstructionReportMode.FUNDING_EXPORT.reportModeName), true); } case 5: { return new ActionForward( buildReportExportForwardURL( reportRunnerForm, mapping, BudgetConstructionReportMode.MONTHLY_EXPORT.reportModeName), true); } } if (reportSet.isEmpty()) { List<String> messageList = new ArrayList<String>(); messageList.add(BCConstants.Report.MSG_REPORT_NO_DATA); SpringContext.getBean(BudgetConstructionReportsServiceHelper.class) .generatePdf(messageList, baos); WebUtils.saveMimeOutputStreamAsFile( response, ReportGeneration.PDF_MIME_TYPE, baos, jasperFileName + ReportGeneration.PDF_FILE_EXTENSION); } else { ResourceBundle resourceBundle = ResourceBundle.getBundle( BCConstants.Report.REPORT_MESSAGES_CLASSPATH, Locale.getDefault()); Map<String, Object> reportData = new HashMap<String, Object>(); reportData.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); SpringContext.getBean(ReportGenerationService.class) .generateReportToOutputStream( reportData, reportSet, BCConstants.Report.REPORT_TEMPLATE_CLASSPATH + jasperFileName, baos); WebUtils.saveMimeOutputStreamAsFile( response, ReportGeneration.PDF_MIME_TYPE, baos, jasperFileName + ReportGeneration.PDF_FILE_EXTENSION); } return null; }
@Override public void process(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { // indicates that we are running in legacy KNS context LegacyUtils.beginLegacyContext(); try { if (LOG.isInfoEnabled()) { LOG.info( new StringBuffer("Started processing request: '") .append(request.getRequestURI()) .append("' w/ query string: '") .append(request.getQueryString()) .append("'")); } try { strutsProcess(request, response); } catch (FileUploadLimitExceededException e) { ActionForward actionForward = processException(request, response, e, e.getActionForm(), e.getActionMapping()); processForwardConfig(request, response, actionForward); } finally { KNSGlobalVariables.setKualiForm(null); } try { ActionForm form = WebUtils.getKualiForm(request); if (form != null && form instanceof KualiDocumentFormBase) { String docId = ((KualiDocumentFormBase) form).getDocId(); if (docId != null) { MDC.put(MDC_DOC_ID, docId); } } String refreshCaller = request.getParameter(KRADConstants.REFRESH_CALLER); if (form != null && KualiDocumentFormBase.class.isAssignableFrom(form.getClass()) && !KRADConstants.QUESTION_REFRESH.equalsIgnoreCase(refreshCaller)) { KualiDocumentFormBase docForm = (KualiDocumentFormBase) form; Document document = docForm.getDocument(); String docFormKey = docForm.getFormKey(); UserSession userSession = (UserSession) request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY); if (WebUtils.isDocumentSession(document, docForm)) { getSessionDocumentService() .setDocumentForm(docForm, userSession, request.getRemoteAddr()); } Boolean exitingDocument = (Boolean) request.getAttribute(KRADConstants.EXITING_DOCUMENT); if (exitingDocument != null && exitingDocument.booleanValue()) { // remove KualiDocumentFormBase object from session and // table. getSessionDocumentService() .purgeDocumentForm( docForm.getDocument().getDocumentNumber(), docFormKey, userSession, request.getRemoteAddr()); } } if (LOG.isInfoEnabled()) { LOG.info( new StringBuffer("Finished processing request: '") .append(request.getRequestURI()) .append("' w/ query string: '") .append(request.getQueryString()) .append("'")); } } finally { // MDC docId key is set above, and also during super.process() in the call to // processActionForm MDC.remove(MDC_DOC_ID); } } finally { LegacyUtils.endLegacyContext(); } }
/** * Checks for return from a lookup or question, and restores the action form stored under the * request parameter docFormKey. */ @Override protected ActionForm processActionForm( HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) { String documentNumber = getDocumentNumber(request); if (documentNumber != null) { MDC.put(MDC_DOC_ID, documentNumber); } UserSession userSession = (UserSession) request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY); String docFormKey = request.getParameter(KRADConstants.DOC_FORM_KEY); String methodToCall = request.getParameter(KRADConstants.DISPATCH_REQUEST_PARAMETER); String refreshCaller = request.getParameter(KRADConstants.REFRESH_CALLER); // String searchListRequestKey = request.getParameter(KRADConstants.SEARCH_LIST_REQUEST_KEY); String documentWebScope = request.getParameter(KRADConstants.DOCUMENT_WEB_SCOPE); if (mapping.getPath().startsWith(KRADConstants.REFRESH_MAPPING_PREFIX) || KRADConstants.RETURN_METHOD_TO_CALL.equalsIgnoreCase(methodToCall) || KRADConstants.QUESTION_REFRESH.equalsIgnoreCase(refreshCaller) || KRADConstants.TEXT_AREA_REFRESH.equalsIgnoreCase(refreshCaller) || KRADConstants.SESSION_SCOPE.equalsIgnoreCase(documentWebScope)) { ActionForm form = null; // check for search result storage and clear GlobalVariables.getUserSession().removeObjectsByPrefix(KRADConstants.SEARCH_LIST_KEY_PREFIX); // We put different type of forms such as document form, lookup form // in session but we only store document form in // database. if (userSession.retrieveObject(docFormKey) != null) { LOG.debug("getDecomentForm KualiDocumentFormBase from session"); form = (ActionForm) userSession.retrieveObject(docFormKey); } else if (StringUtils.isNotBlank(documentNumber)) { form = getSessionDocumentService() .getDocumentForm(documentNumber, docFormKey, userSession, request.getRemoteAddr()); } request.setAttribute(mapping.getAttribute(), form); if (!KRADConstants.SESSION_SCOPE.equalsIgnoreCase(documentWebScope)) { userSession.removeObject(docFormKey); } // we should check whether this is a multipart request because we // could have had a combination of query parameters and a multipart // request String contentType = request.getContentType(); String method = request.getMethod(); if (("POST".equalsIgnoreCase(method) && contentType != null && contentType.startsWith("multipart/form-data"))) { // this method parses the multipart request and adds new // non-file parameters into the request WebUtils.getMultipartParameters(request, null, form, mapping); } // The form can be null if the document is not a session document if (form != null) { return form; } } // Rice has the ability to limit file upload sizes on a per-form basis, // so the max upload sizes may be accessed by calling methods on // PojoFormBase. // This requires that we are able know the file upload size limit (i.e. // retrieve a form instance) before we parse a mulitpart request. ActionForm form = super.processActionForm(request, response, mapping); // for sessiondocument with multipart request String contentType = request.getContentType(); String method = request.getMethod(); if ("GET".equalsIgnoreCase(method) && StringUtils.isNotBlank(methodToCall) && form instanceof PojoForm && ((PojoForm) form) .getMethodToCallsToBypassSessionRetrievalForGETRequests() .contains(methodToCall)) { return createNewActionForm(mapping, request); } // if we have a multipart request, parse it and return the stored form // from session if the doc form key is not blank. If it is blank, then // we just return the form // generated from the superclass processActionForm method. Either way, // we need to parse the mulitpart request now so that we may determine // what the value of the doc form key is. // This is generally against the contract of processActionForm, because // processPopulate should be responsible for parsing the mulitpart // request, but we need to parse it now // to determine the doc form key value. if (("POST".equalsIgnoreCase(method) && contentType != null && contentType.startsWith("multipart/form-data"))) { WebUtils.getMultipartParameters(request, null, form, mapping); docFormKey = request.getParameter(KRADConstants.DOC_FORM_KEY); documentWebScope = request.getParameter(KRADConstants.DOCUMENT_WEB_SCOPE); documentNumber = getDocumentNumber(request); if (KRADConstants.SESSION_SCOPE.equalsIgnoreCase(documentWebScope) || (form instanceof KualiDocumentFormBase && WebUtils.isDocumentSession( ((KualiDocumentFormBase) form).getDocument(), (KualiDocumentFormBase) form))) { Object userSessionObject = userSession.retrieveObject(docFormKey); if (userSessionObject != null && userSessionObject instanceof ActionForm) { LOG.debug("getDocumentForm KualiDocumentFormBase from session"); form = (ActionForm) userSessionObject; } else { ActionForm tempForm = getSessionDocumentService() .getDocumentForm( documentNumber, docFormKey, userSession, request.getRemoteAddr()); if (tempForm != null) { form = tempForm; } } request.setAttribute(mapping.getAttribute(), form); if (form != null) { return form; } } } return form; }
/** * This service is used to print the report. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward print( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContractsGrantsAwardBalancesReportLookupForm awardBalancesReportLookupForm = (ContractsGrantsAwardBalancesReportLookupForm) form; String methodToCall = findMethodToCall(form, request); if (methodToCall.equalsIgnoreCase(KRADConstants.SEARCH_METHOD)) { GlobalVariables.getUserSession().removeObjectsByPrefix(KRADConstants.SEARCH_METHOD); } Lookupable kualiLookupable = awardBalancesReportLookupForm.getLookupable(); if (kualiLookupable == null) { throw new RuntimeException("Lookupable is null."); } List<ResultRow> resultTable = new ArrayList<ResultRow>(); // validate search parameters kualiLookupable.validateSearchParameters(awardBalancesReportLookupForm.getFields()); // this is for 200 limit. turn it off for report. boolean isUnbounded = true; List<ContractsGrantsAwardBalancesReport> displayList = (List<ContractsGrantsAwardBalancesReport>) kualiLookupable.performLookup(awardBalancesReportLookupForm, resultTable, isUnbounded); Object sortIndexObject = GlobalVariables.getUserSession().retrieveObject(ArConstants.SORT_INDEX_SESSION_KEY); if (ObjectUtils.isNull(sortIndexObject) || sortIndexObject.toString() == "0") { sortIndexObject = "0"; } // get sort property String sortPropertyName = getFieldNameForSorting( Integer.parseInt(sortIndexObject.toString()), "ContractsGrantsAwardBalancesReport"); // sort list sortReport(displayList, sortPropertyName); // check field is valid for subtotal boolean isFieldSubtotalRequired = CGConstants.ReportsConstants.awardBalancesReportSubtotalFieldsList.contains( sortPropertyName); Map<String, KualiDecimal> subTotalMap = new HashMap<String, KualiDecimal>(); if (isFieldSubtotalRequired) { subTotalMap = buildSubTotalMap(displayList, sortPropertyName); } // build report ContractsGrantsReportDataHolder awardBalancesReportDataHolder = new ContractsGrantsReportDataHolder(); List<ContractsGrantsAwardBalancesReportDetailDataHolder> details = awardBalancesReportDataHolder.getDetails(); for (ContractsGrantsAwardBalancesReport awardBalancesReportEntry : displayList) { ContractsGrantsAwardBalancesReportDetailDataHolder reportDetail = new ContractsGrantsAwardBalancesReportDetailDataHolder(); // set report data setReportDate(awardBalancesReportEntry, reportDetail); if (isFieldSubtotalRequired) { // set sortedFieldValue for grouping in the report reportDetail.setSortedFieldValue( getPropertyValue(awardBalancesReportEntry, sortPropertyName)); reportDetail.setDisplaySubtotal(true); // set subTotal from subTotalMap reportDetail.setSubTotal( subTotalMap .get(getPropertyValue(awardBalancesReportEntry, sortPropertyName)) .bigDecimalValue()); } else { // set this to empty string for not displaying subtotal reportDetail.setDisplaySubtotal(false); } details.add(reportDetail); } awardBalancesReportDataHolder.setDetails(details); // build search criteria for report buildReportForSearchCriteia( awardBalancesReportDataHolder.getSearchCriteria(), awardBalancesReportLookupForm.getFieldsForLookup()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String reportFileName = SpringContext.getBean(ContractsGrantsAwardBalancesReportService.class) .generateReport(awardBalancesReportDataHolder, baos); WebUtils.saveMimeOutputStreamAsFile( response, ReportGeneration.PDF_MIME_TYPE, baos, reportFileName + ReportGeneration.PDF_FILE_EXTENSION); return null; }
/** Generates the Budget Report and returns pdf. */ public ActionForward performReport( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { OrganizationReportSelectionForm organizationReportSelectionForm = (OrganizationReportSelectionForm) form; String principalId = GlobalVariables.getUserSession().getPerson().getPrincipalId(); BudgetConstructionReportMode reportMode = BudgetConstructionReportMode.getBudgetConstructionReportModeByName( organizationReportSelectionForm.getReportMode()); if (!storeCodeSelections(organizationReportSelectionForm, reportMode, principalId)) { return mapping.findForward(KFSConstants.MAPPING_BASIC); } // validate threshold settings if needed if (reportMode == BudgetConstructionReportMode.REASON_STATISTICS_REPORT || reportMode == BudgetConstructionReportMode.REASON_SUMMARY_REPORT || reportMode == BudgetConstructionReportMode.SALARY_SUMMARY_REPORT) { if (!this.validThresholdSettings( organizationReportSelectionForm.getBudgetConstructionReportThresholdSettings())) { return mapping.findForward(KFSConstants.MAPPING_BASIC); } } // for report exports foward to export action to display formatting screen if (reportMode.export) { String exportUrl = this.buildReportExportForwardURL(organizationReportSelectionForm, mapping); return new ActionForward(exportUrl, true); } // build report data and populate report objects for rendering Collection reportSet = buildReportData( reportMode, organizationReportSelectionForm.getUniversityFiscalYear(), principalId, organizationReportSelectionForm.isReportConsolidation(), organizationReportSelectionForm.getBudgetConstructionReportThresholdSettings()); // build pdf and stream back ByteArrayOutputStream baos = new ByteArrayOutputStream(); // output the report or a message if empty if (reportSet.isEmpty()) { List<String> messageList = new ArrayList<String>(); messageList.add(BCConstants.Report.MSG_REPORT_NO_DATA); SpringContext.getBean(BudgetConstructionReportsServiceHelper.class) .generatePdf(messageList, baos); WebUtils.saveMimeOutputStreamAsFile( response, ReportGeneration.PDF_MIME_TYPE, baos, reportMode.jasperFileName + ReportGeneration.PDF_FILE_EXTENSION); } else { ResourceBundle resourceBundle = ResourceBundle.getBundle( BCConstants.Report.REPORT_MESSAGES_CLASSPATH, Locale.getDefault()); Map<String, Object> reportData = new HashMap<String, Object>(); reportData.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); SpringContext.getBean(ReportGenerationService.class) .generateReportToOutputStream( reportData, reportSet, BCConstants.Report.REPORT_TEMPLATE_CLASSPATH + reportMode.jasperFileName, baos); WebUtils.saveMimeOutputStreamAsFile( response, ReportGeneration.PDF_MIME_TYPE, baos, reportMode.jasperFileName + ReportGeneration.PDF_FILE_EXTENSION); } return null; }