From 6beb446925c967aca92f5513adf36c5db77c00d6 Mon Sep 17 00:00:00 2001 From: TATTAVARADA Date: Thu, 27 Apr 2017 07:53:18 -0400 Subject: [PORTAL-7] Rebase This rebasing includes common libraries and common overlays projects abstraction of components Change-Id: Ia1efa4deacdc5701e6205104ac021a6c80ed60ba Signed-off-by: st782s --- ecomp-sdk/epsdk-analytics/.gitignore | 5 + ecomp-sdk/epsdk-analytics/README.md | 16 + .../epsdk-analytics/license/licenses.properties | 1 + .../epsdk-analytics/license/my_license/header.txt | 11 + .../epsdk-analytics/license/my_license/license.txt | 4 + ecomp-sdk/epsdk-analytics/pom.xml | 209 + .../openecomp/portalsdk/analytics/AntBuild.java | 91 + .../portalsdk/analytics/RaptorObject.java | 44 + .../portalsdk/analytics/config/ConfigLoader.java | 193 + .../portalsdk/analytics/controller/Action.java | 91 + .../analytics/controller/ActionHandler.java | 2417 +++++++ .../analytics/controller/ActionMapping.java | 34 + .../portalsdk/analytics/controller/Controller.java | 125 + .../analytics/controller/ErrorHandler.java | 151 + .../analytics/controller/WizardProcessor.java | 2356 +++++++ .../analytics/controller/WizardSequence.java | 191 + .../controller/WizardSequenceCrossTab.java | 45 + .../controller/WizardSequenceDashboard.java | 40 + .../analytics/controller/WizardSequenceLinear.java | 47 + .../controller/WizardSequenceSQLBasedCrossTab.java | 44 + .../controller/WizardSequenceSQLBasedHive.java | 46 + .../controller/WizardSequenceSQLBasedLinear.java | 47 + .../WizardSequenceSQLBasedLinearDatamining.java | 46 + .../portalsdk/analytics/error/RaptorException.java | 35 + .../analytics/error/RaptorRuntimeException.java | 36 + .../analytics/error/RaptorSchedularException.java | 36 + .../analytics/error/ReportSQLException.java | 51 + .../analytics/error/UserAccessException.java | 34 + .../analytics/error/UserDefinedException.java | 36 + .../analytics/error/ValidationException.java | 42 + .../portalsdk/analytics/gmap/line/Line.java | 86 + .../analytics/gmap/line/LineCollection.java | 158 + .../portalsdk/analytics/gmap/line/LineInfo.java | 190 + .../analytics/gmap/map/ColorProperties.java | 119 + .../analytics/gmap/map/GMapProperties.java | 49 + .../analytics/gmap/map/GeoCoordinate.java | 25 + .../portalsdk/analytics/gmap/map/MapConstant.java | 44 + .../portalsdk/analytics/gmap/map/NovaMap.java | 504 ++ .../analytics/gmap/map/layer/SwingLayer.java | 235 + .../portalsdk/analytics/gmap/node/Node.java | 178 + .../analytics/gmap/node/NodeCollection.java | 188 + .../portalsdk/analytics/gmap/node/NodeInfo.java | 210 + .../portalsdk/analytics/gmap/utils/MapUtils.java | 70 + .../analytics/gmap/utils/SwingWorker.java | 155 + .../portalsdk/analytics/model/DataCache.java | 516 ++ .../portalsdk/analytics/model/ReportHandler.java | 6638 ++++++++++++++++++++ .../portalsdk/analytics/model/ReportLoader.java | 1079 ++++ .../portalsdk/analytics/model/SearchHandler.java | 479 ++ .../analytics/model/base/ChartSeqComparator.java | 49 + .../analytics/model/base/IdNameColLookup.java | 37 + .../portalsdk/analytics/model/base/IdNameList.java | 183 + .../analytics/model/base/IdNameLookup.java | 204 + .../portalsdk/analytics/model/base/IdNameSql.java | 400 ++ .../analytics/model/base/IdNameValue.java | 100 + .../analytics/model/base/NameComparator.java | 34 + .../analytics/model/base/OrderBySeqComparator.java | 37 + .../analytics/model/base/OrderSeqComparator.java | 37 + .../analytics/model/base/ReportSecurity.java | 404 ++ .../analytics/model/base/ReportWrapper.java | 5719 +++++++++++++++++ .../analytics/model/definition/DBColumnInfo.java | 76 + .../model/definition/DrillDownParamDef.java | 111 + .../analytics/model/definition/Marker.java | 79 + .../model/definition/ReportDefinition.java | 1471 +++++ .../analytics/model/definition/ReportLogEntry.java | 89 + .../analytics/model/definition/ReportMap.java | 86 + .../analytics/model/definition/ReportSchedule.java | 1407 +++++ .../analytics/model/definition/SecurityEntry.java | 44 + .../analytics/model/definition/TableJoin.java | 67 + .../analytics/model/definition/TableSource.java | 101 + .../model/definition/wizard/ColumnEditJSON.java | 110 + .../model/definition/wizard/ColumnJSON.java | 41 + .../model/definition/wizard/DefinitionJSON.java | 215 + .../model/definition/wizard/ElementJSON.java | 33 + .../model/definition/wizard/FormEditJSON.java | 113 + .../model/definition/wizard/IdNameBooleanJSON.java | 32 + .../model/definition/wizard/ImportJSON.java | 54 + .../model/definition/wizard/ListJSON.java | 40 + .../model/definition/wizard/MessageJSON.java | 55 + .../model/definition/wizard/NameBooleanJSON.java | 25 + .../model/definition/wizard/QueryJSON.java | 60 + .../model/definition/wizard/QueryResultJSON.java | 70 + .../model/definition/wizard/SearchFieldJSON.java | 41 + .../model/definition/wizard/WizardJSON.java | 9 + .../portalsdk/analytics/model/pdf/PageEvent.java | 256 + .../portalsdk/analytics/model/pdf/PdfBean.java | 242 + .../analytics/model/pdf/PdfReportHandler.java | 1898 ++++++ .../analytics/model/runtime/BarChartOptions.java | 75 + .../analytics/model/runtime/CategoryAxisJSON.java | 24 + .../analytics/model/runtime/ChartD3Helper.java | 4073 ++++++++++++ .../analytics/model/runtime/ChartJSON.java | 451 ++ .../analytics/model/runtime/ChartJSONHelper.java | 1550 +++++ .../analytics/model/runtime/ChartWebRuntime.java | 423 ++ .../model/runtime/CommonChartOptions.java | 81 + .../analytics/model/runtime/ErrorJSONRuntime.java | 58 + .../model/runtime/FlexTimeSeriesChartOptions.java | 38 + .../analytics/model/runtime/FormField.java | 2103 +++++++ .../analytics/model/runtime/FormatProcessor.java | 369 ++ .../portalsdk/analytics/model/runtime/Item.java | 54 + .../analytics/model/runtime/LookupDBInfo.java | 89 + .../analytics/model/runtime/RangeAxisJSON.java | 93 + .../analytics/model/runtime/ReportFormFields.java | 356 ++ .../analytics/model/runtime/ReportJSONRuntime.java | 709 +++ .../model/runtime/ReportParamDateValueParser.java | 196 + .../analytics/model/runtime/ReportParamValues.java | 369 ++ .../runtime/ReportParamValuesForPDFExcel.java | 419 ++ .../analytics/model/runtime/ReportRuntime.java | 3401 ++++++++++ .../model/runtime/TimeSeriesChartOptions.java | 62 + .../analytics/model/runtime/VisualManager.java | 69 + .../analytics/model/search/ReportSearchResult.java | 85 + .../model/search/ReportSearchResultJSON.java | 249 + .../analytics/model/search/SearchResult.java | 212 + .../analytics/model/search/SearchResultColumn.java | 256 + .../analytics/model/search/SearchResultField.java | 214 + .../analytics/model/search/SearchResultJSON.java | 86 + .../analytics/model/search/SearchResultRow.java | 92 + .../analytics/scheduler/SchedulerUtil.java | 369 ++ .../portalsdk/analytics/scheduler/SendEmail.java | 416 ++ .../analytics/scheduler/SendNotifications.java | 462 ++ .../portalsdk/analytics/system/AppUtils.java | 344 + .../analytics/system/ConnectionUtils.java | 69 + .../portalsdk/analytics/system/DbUtils.java | 271 + .../portalsdk/analytics/system/ExecuteQuery.java | 61 + .../portalsdk/analytics/system/Globals.java | 2307 +++++++ .../portalsdk/analytics/system/IAppUtils.java | 177 + .../portalsdk/analytics/system/IDbUtils.java | 36 + .../portalsdk/analytics/system/RDbUtils.java | 35 + .../portalsdk/analytics/system/RemDbUtils.java | 200 + .../analytics/system/fusion/AntBuild.java | 67 + .../analytics/system/fusion/AppUtils.java | 367 ++ .../portalsdk/analytics/system/fusion/DbUtils.java | 78 + .../analytics/system/fusion/RemoteDbUtils.java | 57 + .../adapter/AdapterSessionFactoryContainer.java | 39 + .../analytics/system/fusion/adapter/DateUtils.java | 287 + .../system/fusion/adapter/FusionAdapter.java | 121 + .../analytics/system/fusion/adapter/IdName.java | 67 + .../analytics/system/fusion/adapter/Item.java | 55 + .../analytics/system/fusion/adapter/Lookup.java | 85 + .../system/fusion/adapter/RaptorAdapter.java | 367 ++ .../system/fusion/adapter/SpringContext.java | 37 + .../fusion/controller/FileServletController.java | 206 + .../analytics/system/fusion/domain/CR_Report.java | 307 + .../analytics/system/fusion/domain/QuickLink.java | 61 + .../system/fusion/domain/RaptorSearch.java | 188 + .../analytics/system/fusion/domain/ReportInfo.java | 159 + .../system/fusion/service/RaptorService.java | 35 + .../system/fusion/service/RaptorServiceImpl.java | 183 + .../system/fusion/web/RaptorController.java | 190 + .../system/fusion/web/RaptorControllerAsync.java | 1752 ++++++ .../fusion/web/ReportsSearchListController.java | 77 + .../portalsdk/analytics/util/AppConstants.java | 667 ++ .../portalsdk/analytics/util/DataSet.java | 177 + .../portalsdk/analytics/util/ExcelColorDef.java | 65 + .../portalsdk/analytics/util/HtmlStripper.java | 157 + .../openecomp/portalsdk/analytics/util/Log.java | 40 + .../portalsdk/analytics/util/RemDbInfo.java | 93 + .../portalsdk/analytics/util/SQLCorrector.java | 343 + .../portalsdk/analytics/util/Scheduler.java | 91 + .../openecomp/portalsdk/analytics/util/Utils.java | 372 ++ .../portalsdk/analytics/util/XSSFilter.java | 91 + .../portalsdk/analytics/util/jar/ExtractJar.java | 237 + .../analytics/util/upgrade/SystemUpgrade.java | 127 + .../portalsdk/analytics/view/ColumnHeader.java | 241 + .../portalsdk/analytics/view/ColumnHeaderRow.java | 102 + .../portalsdk/analytics/view/ColumnVisual.java | 74 + .../analytics/view/CrossTabColumnValues.java | 75 + .../analytics/view/CrossTabOrderManager.java | 98 + .../analytics/view/CrossTabTotalValue.java | 56 + .../portalsdk/analytics/view/DataRow.java | 168 + .../portalsdk/analytics/view/DataValue.java | 361 ++ .../portalsdk/analytics/view/HtmlFormatter.java | 205 + .../analytics/view/ReportColumnHeaderRows.java | 71 + .../portalsdk/analytics/view/ReportData.java | 813 +++ .../portalsdk/analytics/view/ReportDataRows.java | 72 + .../analytics/view/ReportRowHeaderCols.java | 71 + .../portalsdk/analytics/view/RowHeader.java | 121 + .../portalsdk/analytics/view/RowHeaderCol.java | 158 + .../analytics/xmlobj/ChartAdditionalOptions.java | 1178 ++++ .../analytics/xmlobj/ChartDrillFormfield.java | 86 + .../analytics/xmlobj/ChartDrillOptions.java | 206 + .../portalsdk/analytics/xmlobj/ColFilterList.java | 93 + .../portalsdk/analytics/xmlobj/ColFilterType.java | 298 + .../analytics/xmlobj/CustomReportType.java | 2011 ++++++ .../analytics/xmlobj/DashboardEditorList.java | 93 + .../analytics/xmlobj/DashboardEditorReport.java | 172 + .../analytics/xmlobj/DashboardReports.java | 93 + .../analytics/xmlobj/DashboardReportsNew.java | 147 + .../portalsdk/analytics/xmlobj/DataColumnList.java | 95 + .../portalsdk/analytics/xmlobj/DataColumnType.java | 1455 +++++ .../portalsdk/analytics/xmlobj/DataSourceList.java | 93 + .../portalsdk/analytics/xmlobj/DataSourceType.java | 281 + .../analytics/xmlobj/DataminingOptions.java | 167 + .../portalsdk/analytics/xmlobj/FormFieldList.java | 120 + .../portalsdk/analytics/xmlobj/FormFieldType.java | 610 ++ .../portalsdk/analytics/xmlobj/FormatList.java | 95 + .../portalsdk/analytics/xmlobj/FormatType.java | 366 ++ .../analytics/xmlobj/JavascriptItemType.java | 144 + .../portalsdk/analytics/xmlobj/JavascriptList.java | 93 + .../portalsdk/analytics/xmlobj/Marker.java | 167 + .../portalsdk/analytics/xmlobj/ObjectFactory.java | 305 + .../analytics/xmlobj/PDFAdditionalOptions.java | 340 + .../analytics/xmlobj/PredefinedValueList.java | 93 + .../portalsdk/analytics/xmlobj/ReportMap.java | 444 ++ .../portalsdk/analytics/xmlobj/Reports.java | 113 + .../portalsdk/analytics/xmlobj/SemaphoreList.java | 93 + .../portalsdk/analytics/xmlobj/SemaphoreType.java | 227 + 205 files changed, 72088 insertions(+) create mode 100644 ecomp-sdk/epsdk-analytics/.gitignore create mode 100644 ecomp-sdk/epsdk-analytics/README.md create mode 100644 ecomp-sdk/epsdk-analytics/license/licenses.properties create mode 100644 ecomp-sdk/epsdk-analytics/license/my_license/header.txt create mode 100644 ecomp-sdk/epsdk-analytics/license/my_license/license.txt create mode 100644 ecomp-sdk/epsdk-analytics/pom.xml create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/AntBuild.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/RaptorObject.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/config/ConfigLoader.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Action.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionHandler.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionMapping.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Controller.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ErrorHandler.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardProcessor.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequence.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceCrossTab.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceDashboard.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceLinear.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedCrossTab.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedHive.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinear.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinearDatamining.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorRuntimeException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorSchedularException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ReportSQLException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserAccessException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserDefinedException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ValidationException.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/Line.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineCollection.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineInfo.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/ColorProperties.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GMapProperties.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GeoCoordinate.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/MapConstant.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/NovaMap.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/layer/SwingLayer.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/Node.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeCollection.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeInfo.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/MapUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/SwingWorker.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/DataCache.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportHandler.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportLoader.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/SearchHandler.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ChartSeqComparator.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameColLookup.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameLookup.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameSql.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameValue.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/NameComparator.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderBySeqComparator.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderSeqComparator.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportSecurity.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportWrapper.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DBColumnInfo.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DrillDownParamDef.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/Marker.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportDefinition.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportLogEntry.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportMap.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportSchedule.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/SecurityEntry.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableJoin.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableSource.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnEditJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/DefinitionJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ElementJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/FormEditJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/IdNameBooleanJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ImportJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ListJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/MessageJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/NameBooleanJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryResultJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/SearchFieldJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/WizardJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PageEvent.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfBean.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfReportHandler.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/BarChartOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CategoryAxisJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartD3Helper.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSONHelper.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartWebRuntime.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CommonChartOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ErrorJSONRuntime.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FlexTimeSeriesChartOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FormField.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FormatProcessor.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/Item.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/LookupDBInfo.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/RangeAxisJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ReportFormFields.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ReportJSONRuntime.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ReportParamDateValueParser.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ReportParamValues.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ReportParamValuesForPDFExcel.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ReportRuntime.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/TimeSeriesChartOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/VisualManager.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/ReportSearchResult.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/ReportSearchResultJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/SearchResult.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/SearchResultColumn.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/SearchResultField.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/SearchResultJSON.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/search/SearchResultRow.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/scheduler/SchedulerUtil.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/scheduler/SendEmail.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/scheduler/SendNotifications.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/AppUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/ConnectionUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/DbUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/ExecuteQuery.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/Globals.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/IAppUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/IDbUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/RDbUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/RemDbUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AntBuild.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AppUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/DbUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/RemoteDbUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/AdapterSessionFactoryContainer.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/DateUtils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/FusionAdapter.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/IdName.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Item.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Lookup.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/RaptorAdapter.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/SpringContext.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/controller/FileServletController.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/CR_Report.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/QuickLink.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/RaptorSearch.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/ReportInfo.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorService.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorServiceImpl.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorController.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorControllerAsync.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/ReportsSearchListController.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/AppConstants.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/DataSet.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/ExcelColorDef.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/HtmlStripper.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/Log.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/RemDbInfo.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/SQLCorrector.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/Scheduler.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/Utils.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/XSSFilter.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/jar/ExtractJar.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/util/upgrade/SystemUpgrade.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ColumnHeader.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ColumnHeaderRow.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ColumnVisual.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/CrossTabColumnValues.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/CrossTabOrderManager.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/CrossTabTotalValue.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/DataRow.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/DataValue.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/HtmlFormatter.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ReportColumnHeaderRows.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ReportData.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ReportDataRows.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/ReportRowHeaderCols.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/RowHeader.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/view/RowHeaderCol.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ChartAdditionalOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ChartDrillFormfield.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ChartDrillOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ColFilterList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ColFilterType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/CustomReportType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DashboardEditorList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DashboardEditorReport.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DashboardReports.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DashboardReportsNew.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DataColumnList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DataColumnType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DataSourceList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DataSourceType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/DataminingOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/FormFieldList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/FormFieldType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/FormatList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/FormatType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/JavascriptItemType.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/JavascriptList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/Marker.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ObjectFactory.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/PDFAdditionalOptions.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/PredefinedValueList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/ReportMap.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/Reports.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/SemaphoreList.java create mode 100644 ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/xmlobj/SemaphoreType.java (limited to 'ecomp-sdk/epsdk-analytics') diff --git a/ecomp-sdk/epsdk-analytics/.gitignore b/ecomp-sdk/epsdk-analytics/.gitignore new file mode 100644 index 00000000..aa0c881b --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/.gitignore @@ -0,0 +1,5 @@ +/target +/bin/ +/.settings/ +.project +.classpath diff --git a/ecomp-sdk/epsdk-analytics/README.md b/ecomp-sdk/epsdk-analytics/README.md new file mode 100644 index 00000000..be0b376c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/README.md @@ -0,0 +1,16 @@ +# ECOMP Portal SDK Analytics + +## Overview + +This is the Maven project for the ECOMP Portal SDK Analytics library, +which is distributed as epsdk-analytics-N.N.N.jar. This library +requires Hibernate and Spring, and provides data-visualization +features including charts, maps and reports ("Raptor"). + +## Release Notes + +Version 1.1.0 +- [Portal-7] Improvements added as part of the rebasing process + +Version 1.0.0 +- Initial release diff --git a/ecomp-sdk/epsdk-analytics/license/licenses.properties b/ecomp-sdk/epsdk-analytics/license/licenses.properties new file mode 100644 index 00000000..4b0e28e7 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/license/licenses.properties @@ -0,0 +1 @@ +my_license=My license diff --git a/ecomp-sdk/epsdk-analytics/license/my_license/header.txt b/ecomp-sdk/epsdk-analytics/license/my_license/header.txt new file mode 100644 index 00000000..c026b6b7 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/license/my_license/header.txt @@ -0,0 +1,11 @@ +Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + +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. diff --git a/ecomp-sdk/epsdk-analytics/license/my_license/license.txt b/ecomp-sdk/epsdk-analytics/license/my_license/license.txt new file mode 100644 index 00000000..bf326153 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/license/my_license/license.txt @@ -0,0 +1,4 @@ +name=my_license +description= +licenseURL= +headerURL= \ No newline at end of file diff --git a/ecomp-sdk/epsdk-analytics/pom.xml b/ecomp-sdk/epsdk-analytics/pom.xml new file mode 100644 index 00000000..41be4f28 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/pom.xml @@ -0,0 +1,209 @@ + + + 4.0.0 + + + org.openecomp.ecompsdkos + epsdk-project + 1.1.0-SNAPSHOT + + + + epsdk-analytics + + jar + ECOMP Portal SDK Analytics + Provides analytics features for SDK applications + https://wiki.onap.org/display/DW/Portal + + + + + + + + + + + + + + org.openecomp.ecompsdkos + epsdk-core + ${project.version} + + + + com.fasterxml.jackson.core + jackson-annotations + 2.6.3 + + + com.fasterxml.jackson.core + jackson-core + 2.6.3 + + + com.fasterxml.jackson.core + jackson-databind + 2.6.3 + + + + + commons-codec + commons-codec + 1.10 + + + commons-lang + commons-lang + 2.6 + + + javax.servlet + javax.servlet-api + 3.1.0 + + + + com.lowagie + itext + 2.0.8 + + + + org.slf4j + jcl-over-slf4j + 1.7.12 + + + org.springframework + spring-core + ${springframework.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-orm + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + org.apache.poi + poi + 3.5-FINAL + + + commons-logging + commons-logging + + + log4j + log4j + + + + + org.apache.poi + poi-ooxml + 3.5-FINAL + + + commons-logging + commons-logging + + + log4j + log4j + + + + + org.apache.poi + poi-scratchpad + 3.5-FINAL + + + commons-logging + commons-logging + + + log4j + log4j + + + + + org.apache.poi + poi-contrib + 3.5-FINAL + + + commons-logging + commons-logging + + + log4j + log4j + + + + + + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/AntBuild.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/AntBuild.java new file mode 100644 index 00000000..7065c9b9 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/AntBuild.java @@ -0,0 +1,91 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics; + +import java.io.IOException; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +/** + * @author sundar + * This class is used to get version and Build information when + * user run "java -jar raptor_classes.jar" command. + */ +public class AntBuild { + + public static String buildNum = ""; + + public static void main(String[] args) { + System.out.println("Jar (raptor_classes.jar) Information: "); + readManifest(); + } + + public static void readManifest() { + try { + Class clazz = AntBuild.class; + String classContainer = clazz.getProtectionDomain().getCodeSource().getLocation().toString(); + URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF"); + Manifest manifest = new Manifest(manifestUrl.openStream()); + + //JarFile jar = new JarFile("../lib/raptor_classes.jar"); + //Manifest manifest = jar.getManifest(); + + Attributes attribs = manifest.getMainAttributes(); + Iterator it = attribs.entrySet().iterator(); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + Attributes.Name attributeName = (Attributes.Name) entry.getKey(); + String attributeValue = (String) entry.getValue(); + if (attributeName.toString().equals("Created-By")) + System.out.println("Java HotSpot(TM) Client VM " + " : " + attributeValue); + else if (attributeName.toString().equals("Java-Version")) + System.out.println("Java Version " + " : " + attributeValue); + else if (attributeName.toString().equals("Java-Runtime-Version")) + System.out.println("Java Runtime Version " + " : " + attributeValue); + else if (attributeName.toString().equals("Ant-Version")) + System.out.println(attributeName.toString() + " : " + attributeValue); + else { + if(attributeName.toString().startsWith("Raptor")) { + if (attributeName.toString().startsWith("Raptor-Build-Version")) + buildNum = attributeValue; + System.out.println(attributeName.toString() + " : " + attributeValue); + } + } + } + + } catch (IOException e) { + System.err.println("Cannot read jar-file manifest: " + + e.getMessage()); + } + } + + public static String getBuildNum() { + if (buildNum.length()>0) + return buildNum; + else { + readManifest(); + return buildNum; + } + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/RaptorObject.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/RaptorObject.java new file mode 100644 index 00000000..9a45c19c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/RaptorObject.java @@ -0,0 +1,44 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics; + +public class RaptorObject extends java.lang.Object { + + protected String nvl(String s) { + return (s == null) ? "" : s; + } + + protected String nvl(String s, String sDefault) { + return nvl(s).equals("") ? sDefault : s; + } + + protected static String nvls(String s) { + return (s == null) ? "" : s; + } + + protected static String nvls(String s, String sDefault) { + return nvls(s).equals("") ? sDefault : s; + } + + protected boolean getFlagInBoolean(String s) { + return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true"); + } + +} // RaptorObject diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/config/ConfigLoader.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/config/ConfigLoader.java new file mode 100644 index 00000000..2aa8b7bd --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/config/ConfigLoader.java @@ -0,0 +1,193 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.config; + +import java.io.*; +import java.util.*; +import javax.servlet.*; + +import org.openecomp.portalsdk.analytics.controller.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class ConfigLoader { + // public static final String RAPTOR_ACTION_MAP = + // "raptor_action_map.properties"; + + private static final String P_FILE_EXTENSION = ".properties"; + + public static final String RAPTOR_PROPERTIES = "raptor"; + + public static final String SQL_PROPERTIES = "sql"; + + public static final String APP_PROPERTIES = "raptor_app"; + + public static final String DB_PROPERTIES = "raptor_db"; + + private static String configFilesPath = "/WEB-INF/conf/"; + + public static final String RAPTOR_PDF_PROPERTIES = "raptor_pdf"; + + // private static String internalFilesPath = + // "/WEB-INF/classes/org/openecomp/portalsdk/analytics/config"; // Used for internal files that + // are not supposed to be modified by the user; may be unavailable in some + // cases - so defaults are expected + + private static String raptorActionMapString = + "report.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_run.jsp \n" + + "mobile.report.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |mobile_report_run.jsp \n" + + "report.dashrep1.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportDashRep1 |report_run_dashrep1.jsp \n" + + "report.dashrep2.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportDashRep2 |report_run_dashrep2.jsp \n" + + "report.dashrep3.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportDashRep3 |report_run_dashrep3.jsp \n" + + "report.dashrep4.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportDashRep4 |report_run_dashrep4.jsp \n" + + "report.download |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_xls.jsp \n" + + "report.download.excel2007 |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_xlsx.jsp \n" + + "report.download.page |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_page_xls.jsp \n" + + "report.csv.download |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_csv.jsp \n" + + "report.text.download |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_txt.jsp \n" + + "report.search |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportSearch |report_search.jsp \n" + + "report.search.execute |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportSearchExecute |report_search \n" + + "report.search.user |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportSearchUser |report_search.jsp \n" + + "report.search.public |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportSearchPublic |report_search.jsp \n" + + "report.search.favorite |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportSearchFavorites |report_search.jsp \n" + + "report.wizard |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportWizard |report_wizard \n" + + "report.create |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportCreate |report_wizard \n" + + "report.import |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_import \n" + + "report.import.save |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportImportSave |report_wizard \n" + + "report.copy |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportCopy |report_wizard \n" + + "report.copy.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportCopy |raptor_wizard_container.jsp \n" + + "report.edit |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportEdit |report_wizard \n" + + "report.delete |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportDelete |report_search \n" + + "report.popup.field |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportFormFieldPopup |popup_field.jsp \n" + + "report.popup.map |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportValuesMapDefPopup |popup_map.jsp \n" + + "report.popup.drilldown.table |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_drill_down_table.jsp \n" + + "report.popup.drilldown.report|org.openecomp.portalsdk.analytics.controller.ActionHandler|reportDrillDownToReportDefPopup|popup_drill_down_report \n" + + "report.popup.import.semaphore|org.openecomp.portalsdk.analytics.controller.ActionHandler|importSemaphorePopup |popup_import_semaphore \n" + + "report.popup.semaphore |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_semaphore \n" + + "report.popup.semaphore.save |org.openecomp.portalsdk.analytics.controller.ActionHandler|saveSemaphorePopup |popup_semaphore \n" + + "report.popup.filter.col |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_filter_col.jsp \n" + + "report.popup.filter.data |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportFilterDataPopup |popup_filter_data.jsp \n" + + "report.popup.sql |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportShowSQLPopup |popup_sql \n " + + "report.run.popup |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_run_popup.jsp \n" + + "report.popup.test.cond |org.openecomp.portalsdk.analytics.controller.ActionHandler|testSchedCondPopup |popup_sql \n" + + "report.popup.testrun.sql |org.openecomp.portalsdk.analytics.controller.ActionHandler|testRunSQLPopup |popup_testrun_sql \n" + + "report.test.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |test_run_sql \n" + + "report.field.testrun.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |test_field_run_sql \n" + + "report.field.default.testrun.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |default_field_run_sql \n" + + "report.field.date.start.testrun.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |date_start_field_run_sql \n" + + "report.field.date.end.testrun.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |date_end_field_run_sql \n" + + "report.popup.table.cols |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_table_cols \n" + + "refresh.cache |org.openecomp.portalsdk.analytics.controller.ActionHandler|refreshCache |message.jsp \n" + + "report.message |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |message.jsp \n" + + "report.download.pdf |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_pdf.jsp \n" + + "report.popup.pdfconfig |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_pdf_config.jsp \n" + + "download.all |org.openecomp.portalsdk.analytics.controller.ActionHandler|downloadAll |close.jsp \n" + + "download.all.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_download_flat_file.jsp \n" + + "download.data.file |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |download_data_file.jsp \n" + + "popup.calendar |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |gtm_calendar.jsp \n" + + "report.folderlist |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |folder_report_list.jsp \n" + + "report.folderlist_iframe |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |folder_report_list_iframe.jsp \n" + + "report.childDropDown |org.openecomp.portalsdk.analytics.controller.ActionHandler|getChildDropDown |raptor_childdropdown.jsp \n" + + "report.create.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_create_container.jsp \n" + + "report.search.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_container.jsp \n" + + "report.search.execute.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_execute_container.jsp \n" + + "report.search.user.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_user_container.jsp \n" + + "report.search.public.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_public_container.jsp \n" + + "report.search.favorite.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_favorite_container.jsp \n" + + "report.run.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_run_container.jsp \n" + + "report.formfields.run.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|formFieldRun |report_run_container.jsp \n" + + "report.run.jsp |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_run.jsp \n" + + "report.schedule.multiple |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |wizard_schedule_multiple.jsp \n" + + "report.schedule.submit |org.openecomp.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only.jsp \n" + + "report.schedule.report.submit |org.openecomp.portalsdk.analytics.controller.ActionHandler|processScheduleReportList |wizard_schedule_only.jsp \n" + + "report.schedule.report.submit_wmenu |org.openecomp.portalsdk.analytics.controller.ActionHandler|processScheduleReportList |wizard_schedule_only_from_search.jsp \n" + + "report.schedule_only |org.openecomp.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only \n" + + "report.schedule_only_from_search |org.openecomp.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only_from_search.jsp \n" + + "report.schedule_delete |org.openecomp.portalsdk.analytics.controller.ActionHandler|processScheduleDelete |report_run_container.jsp \n" + + "report.schedule.submit_from_search |org.openecomp.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only_from_search.jsp \n" + + "report.dashboard.detail |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |dashboard_report_run_detail.jsp \n" + + "report.csv.download.direct |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_csv.jsp \n" + + "report.csv.download.direct |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_csv.jsp \n" + + "report.download.csv.session |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_csv \n" + + "report.download.excel2007.session |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_xlsx.jsp \n" + + "report.download.excel.session |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_xls.jsp \n" + + "report.download.pdf.session |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_pdf.jsp \n" + + "report.download.page.session |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_page_xls.jsp \n" + + "report.data.remove.session |org.openecomp.portalsdk.analytics.controller.ActionHandler|removeReportDataFromSession |report_run_container.jsp \n" + + "report.dashboard.run.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_dashboard_run_container.jsp \n" + + "chart.force.cluster |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |force_cluster.jsp \n" + + "chart.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportChartRun |report_run_container.jsp \n" + + "chart.json |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportChartRun |report_run_container.jsp \n" + + "chart.data.json |org.openecomp.portalsdk.analytics.controller.ActionHandler|reportChartDataRun |report_run_container.jsp \n" + + "quicklinks.json |org.openecomp.portalsdk.analytics.controller.ActionHandler|getQuickLinksJSON |report_run_container.jsp \n" + + "embed.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_embed_run_container.zul \n" + + "schedule.edit |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |wizard_adhoc_schedule.zul \n" + + "chart.annotations.run |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |plugin_chart_annotation.jsp \n" + + "chart.annotations.exec |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |chart_annotations.jsp \n" + + "chart.mini |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |chart_minified.jsp \n" + + "report.olap.run.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_olap_run_container.jsp \n" + + "report.hive.run.container |org.openecomp.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_hive_run_container.jsp \n" + + ; + + private ConfigLoader() { + } + + public static void setConfigFilesPath(String path) { + configFilesPath = path; + } // setConfigFilesPath + + public static Properties getProperties(ServletContext servletContext, String propertiesFile) + throws IOException { + return getProperties(servletContext, propertiesFile, null); + } // getProperties + + public static Properties getProperties(ServletContext servletContext, + String propertiesFile, String systemTypeExtension) throws IOException { + Properties p = new Properties(); + p.load(servletContext.getResourceAsStream(configFilesPath + propertiesFile + + ((systemTypeExtension == null) ? "" : "_" + systemTypeExtension) + + P_FILE_EXTENSION)); + return p; + } // getProperties + + public static ActionMapping loadRaptorActionMapping(ServletContext servletContext) + throws IOException { + ActionMapping actionMapping = new ActionMapping(); + + String pLine = null; + // BufferedReader pFile = new BufferedReader(new + // InputStreamReader(servletContext.getResourceAsStream(internalFilesPath+RAPTOR_ACTION_MAP))); + BufferedReader pFile = new BufferedReader(new StringReader(raptorActionMapString)); + while ((pLine = pFile.readLine()) != null) + if (pLine.trim().length() > 0) + try { + actionMapping.addAction(Action.parse(pLine)); + } catch (Exception e) { + Log + .write("[ConfigLoader.loadRaptorActionMapping] Error - unable to parse action [" + + pLine + "]"); + } + pFile.close(); + + return actionMapping; + } // loadRaptorActionMapping + +} // ConfigLoader + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Action.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Action.java new file mode 100644 index 00000000..853901fb --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Action.java @@ -0,0 +1,91 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; + +public class Action extends org.openecomp.portalsdk.analytics.RaptorObject { + private String action = null; + + private String controllerClass = null; + + private String controllerMethod = null; + + private String jspName = null; + + private Action() { + } + + public Action(String action, String controllerClass, String controllerMethod, + String jspName) { + setAction(action); + setControllerClass(controllerClass); + setControllerMethod(controllerMethod); + setJspName(jspName); + } // Action + + public static Action parse(String configFileEntry) { + Action a = new Action(); + + StringTokenizer st = new StringTokenizer(configFileEntry, "| \t", false); + // if(st.hasMoreTokens()) + a.setAction(st.nextToken()); + a.setControllerClass(st.nextToken()); + a.setControllerMethod(st.nextToken()); + a.setJspName(st.nextToken()); + + return a; + } // parse + + public String getAction() { + return action; + } + + public String getControllerClass() { + return controllerClass; + } + + public String getControllerMethod() { + return controllerMethod; + } + + public String getJspName() { + return jspName; + } + + private void setAction(String action) { + this.action = action; + } + + private void setControllerClass(String controllerClass) { + this.controllerClass = controllerClass; + } + + private void setControllerMethod(String controllerMethod) { + this.controllerMethod = controllerMethod; + } + + private void setJspName(String jspName) { + this.jspName = jspName; + } + +} // Action diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionHandler.java new file mode 100644 index 00000000..d030c994 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionHandler.java @@ -0,0 +1,2417 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * ActionHandler.java - This class is used to call actions related to reports. + * ------------------------------------------------------------------------------------------- + * + * + * + * Changes + * ------- + * 31-Aug-2009 : Version 8.5.1 (Sundar);
  • reportFormFieldPopup iterates form field collections.
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 13-Aug-2009 : Version 8.5 (Sundar);
  • reportFormFieldPopup is changed to have effect on textfield with popup.
+ * 06-Aug-2009 : Version 9.0 (Sundar);
  • reportFormFieldPopupB is changed.
+ * 29-Jul-2009 : Version 8.4 (Sundar);
  • Previously report data for dashboard stored only page level data. This has been changed to show all the data up to the maximum specified.
+ * 27-Jul-2009 : Version 8.4 (Sundar);
  • Bug due to not showing back button after child report in drilldown is navigated more than + * one page is resolved.
+ * 14-Jul-2009 : Version 8.4 (Sundar);
  • Dashboard reports can now be generated excel as separate sheets or group together in PDF. + * They can also be scheduled.
+ * + */ +package org.openecomp.portalsdk.analytics.controller; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException; +import org.openecomp.portalsdk.analytics.error.RaptorSchedularException; +import org.openecomp.portalsdk.analytics.error.ReportSQLException; +import org.openecomp.portalsdk.analytics.error.UserDefinedException; +import org.openecomp.portalsdk.analytics.error.ValidationException; +import org.openecomp.portalsdk.analytics.model.DataCache; +import org.openecomp.portalsdk.analytics.model.ReportHandler; +import org.openecomp.portalsdk.analytics.model.ReportLoader; +import org.openecomp.portalsdk.analytics.model.SearchHandler; +import org.openecomp.portalsdk.analytics.model.base.IdNameColLookup; +import org.openecomp.portalsdk.analytics.model.base.IdNameList; +import org.openecomp.portalsdk.analytics.model.base.IdNameSql; +import org.openecomp.portalsdk.analytics.model.base.ReportSecurity; +import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition; +import org.openecomp.portalsdk.analytics.model.definition.ReportSchedule; +import org.openecomp.portalsdk.analytics.model.runtime.ChartWebRuntime; +import org.openecomp.portalsdk.analytics.model.runtime.ErrorJSONRuntime; +import org.openecomp.portalsdk.analytics.model.runtime.FormField; +import org.openecomp.portalsdk.analytics.model.runtime.FormatProcessor; +import org.openecomp.portalsdk.analytics.model.runtime.ReportFormFields; +import org.openecomp.portalsdk.analytics.model.runtime.ReportJSONRuntime; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.model.runtime.VisualManager; +import org.openecomp.portalsdk.analytics.model.search.ReportSearchResultJSON; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.system.DbUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.system.fusion.domain.QuickLink; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.view.DataRow; +import org.openecomp.portalsdk.analytics.view.DataValue; +import org.openecomp.portalsdk.analytics.view.ReportData; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +public class ActionHandler extends org.openecomp.portalsdk.analytics.RaptorObject { + + //private static Log debugLogger = LogFactory.getLog(ActionHandler.class.getName()); + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ActionHandler.class); + + private void preserveReportRuntimeAsBackup(HttpServletRequest request) { + HttpSession session = request.getSession(); + ArrayList repAl = null; + + if(session.getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST)!=null) + repAl = ((ArrayList)session.getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST)); + int index = Integer.parseInt(nvl((String) session.getAttribute(AppConstants.DRILLDOWN_INDEX), "0")); + int form_index = Integer.parseInt(nvl((String) session.getAttribute(AppConstants.FORM_DRILLDOWN_INDEX), "0")); + int flag = 0; + if(repAl ==null || repAl.size() <= 0) { + //session.setAttribute(AppConstants.SI_BACKUP_FOR_REP_ID, ((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID()); + //session.setAttribute(AppConstants.SI_REPORT_RUN_BACKUP, request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)); + repAl = new ArrayList(); + repAl.add((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)); + + } else { + if(Globals.getMaxDrillDownLevel() < repAl.size()) { + repAl.remove(0); + if(index > 0) index--; + } else if(index < repAl.size()) + repAl.remove(index); + repAl.add(index, (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)); + } + index = index + 1; + // needed to differentiate form and report index to store form parameters for ZK + form_index = form_index + 1; + session.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index)); + session.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index)); + request.getSession().setAttribute(AppConstants.DRILLDOWN_REPORTS_LIST, repAl); + } // preserveReportRuntimeAsBackup + + private void clearReportRuntimeBackup(HttpServletRequest request) { +// debugLogger.debug("in Action Handler clear is been called."); + HttpSession session = request.getSession(); + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + request.removeAttribute(AppConstants.DRILLDOWN_INDEX); + request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + Enumeration enum1 = session.getAttributeNames(); + String attributeName = ""; + while(enum1.hasMoreElements()) { + attributeName = enum1.nextElement(); + if(attributeName.startsWith("parent_")) { + session.removeAttribute(attributeName); + } + } + //request.getSession().removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP); + //request.getSession().removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID); + } // clearReportRuntimeBackup + + private boolean isDashboardInDrillDownList(HttpServletRequest request) throws RaptorException { + ArrayList aL = (ArrayList) request.getSession().getAttribute( + AppConstants.DRILLDOWN_REPORTS_LIST); + ReportRuntime rr = null; + if(aL ==null || aL.size() <= 0) { + return false; + } else { + for (int i =0; i0 ? --index : 0; + form_index = form_index>0 ? --form_index : 0; + request.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index)); + session.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index)); + request.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index)); + session.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index)); + + rr = (ReportRuntime)aL.get(index); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + //clearReportRuntimeBackup(request); + //} + return rr; + } // getReportRuntimeFromBackup + + public String reportRun(HttpServletRequest request, String nextPage) { + String action = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action")); + ReportRuntime rr = null; + String userId = null; + String formFields = ""; + ReportData rd = null; + boolean isEmailAttachment = false; + boolean fromDashboard = AppUtils.getRequestFlag(request,"fromDashboard"); + request.getSession().setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request)); + + boolean rDisplayContent = AppUtils.getRequestFlag(request, + AppConstants.RI_DISPLAY_CONTENT) + || AppUtils.getRequestFlag(request, "noFormFields"); + + try { + //if "refresh=Y" is in request parameter, session variables are removed. + if(AppUtils.getRequestFlag(request, AppConstants.RI_REFRESH)) { + removeVariablesFromSession(request); + } + + + long currentTime = System.currentTimeMillis(); + request.setAttribute("triggeredStartTime", new Long(currentTime)); + String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action")); + String pdfAttachmentKey = AppUtils.getRequestNvlValue(request, "pdfAttachmentKey"); + String parent = ""; + int parentFlag = 0; + if(!nvl(request.getParameter("parent"), "").equals("N")) parent = nvl(request.getParameter("parent"), ""); + if(parent.startsWith("parent_")) parentFlag = 1; + + if (pdfAttachmentKey.length()<=0) { + if(actionKey.equals("report.download.page") || actionKey.equals("report.download") || actionKey.equals("report.download.pdf") || actionKey.equals("report.download.excel2007") || actionKey.equals("report.csv.download") || actionKey.equals("report.text.download")) { + if(parentFlag == 1) rr = (ReportRuntime) request.getSession().getAttribute(parent+"_rr"); + if(rr==null) + rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); //changing session to request + if(!(rr!=null && fromDashboard)) { + userId = AppUtils.getUserID(request); + boolean isFromReportLog = AppUtils.getRequestFlag(request, "fromReportLog"); + int downloadLimit = 0; + if(rr!=null) + downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + if(actionKey.equals("report.csv.download")) + downloadLimit = Globals.getCSVDownloadLimit(); + + if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) { + String sql_whole = rr.getReportDataSQL(userId, downloadLimit, request); + request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole); + } else if(rr!=null && rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + rd = rr.loadReportData(-1, userId, downloadLimit,request, false); /* TODO: should be changed to true */ + request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd); + } + if(!isFromReportLog) { + if(pdfAttachmentKey!=null && pdfAttachmentKey.length()>0) { + if(actionKey.equals("report.download")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCEL, formFields); + } else if (actionKey.equals("report.download.pdf")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_PDF, formFields); + } else if (actionKey.equals("report.download.excel2007")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCELX, formFields); + } + } else { + if(actionKey.equals("report.download") ) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_EXCEL, formFields); + } else if (actionKey.equals("report.download.pdf")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_PDF, formFields); + } else if (actionKey.equals("report.csv.download")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_CSV, formFields); + } else if (actionKey.equals("report.text.download")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_TEXT, formFields); + } else if (actionKey.equals("report.download.page")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_PAGE_EXCEL, formFields); + } else if (actionKey.equals("report.download.excel2007")) { + rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_EXCELX, formFields); + } + } + } + return nextPage; + } + + } + }// pdfAttachmentKey + String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); //changing session to request + + String reportIDFromSession = (rr!=null)?rr.getReportID():""; + logger.debug(EELFLoggerDelegate.debugLogger, ("in Action Handler ********** " + reportID + " " + reportIDFromSession + " "+ actionKey)); +// ReportRuntime rr = (ReportRuntime) request.getAttribute(AppConstants.SI_REPORT_RUNTIME); + logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^^report ID from session " + ((rr!=null)?rr.getReportID():"no report id in session"))); + // if(rr!=null && !(rr.getReportID().equals(reportID))) { +// rr = null; +// request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, null); +// } + + ReportHandler rh1 = new ReportHandler(); + ReportRuntime rr1 = null; + + //debugLogger.debug("Report ID B4 rr1 in ActionHandler " + // + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); + + + //try { + boolean isGoBackAction = AppUtils.getRequestFlag(request, AppConstants.RI_GO_BACK); + + if (AppUtils.getRequestFlag(request, AppConstants.RI_SHOW_BACK_BTN) && !isGoBackAction) { + // debugLogger.debug("Preserving report"); + if(!reportID.equals(reportIDFromSession)) + preserveReportRuntimeAsBackup(request); + } + + if(reportID !=null) + rr1 = rh1.loadReportRuntime(request, reportID, true, 1); + //} catch(Exception e) { + + // } +// debugLogger.debug("Report ID After rr1 in ActionHandler " +// + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); + if(rr1!=null && rr1.getReportType().equals(AppConstants.RT_DASHBOARD)) { + int DASH=7; + int requestFlag = DASH; + ReportHandler rh = new ReportHandler(); + // Added below statement to add parent dashboard report id in session. + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID); + //rr = null; + // get dashboard HTML from report runtime. getListOfReportsFromDashBoardHTML + String strHTML = rr1.getDashboardLayoutHTML(); + + //System.out.println("StrHTML " + strHTML); + // call getListOfReportsFromDashBoardHTML returns HashMap + + TreeMap treeMap = getListOfReportsFromDashBoardHTML(strHTML); + //System.out.println("Size " + hashMap.size()); + Set set = treeMap.entrySet(); + String value = ""; + + HashMap reportsRuntimeMap = new HashMap(); + HashMap reportDataMap = new HashMap(); + HashMap reportChartDataMap = new HashMap(); + // displayTypeMap differentiates whether report need to be displayed as data or chart + HashMap reportDisplayTypeMap = new HashMap(); + + userId = null; + userId = AppUtils.getUserID(request); + int pageNo = -1; + //int downloadLimit = (rr1.getMaxRowsInExcelDownload()>0)?rr1.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + int downloadLimit = 0; + int rep_idx = 0; + int widthFlag = 0; + int heightFlag = 0; + ReportRuntime rrDashboardReports = null; + Integer intObj = null; + ReportRuntime similiarReportRuntime = null; + rd = null; + DataSet ds = null; + String reportIDFromMap = null; + int record = 0; + boolean buildReportdata = true; + + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + record++; + Map.Entry entry = (Entry) iter.next(); + //System.out.println("Key "+ entry.getKey()); + //System.out.println("Value "+ entry.getValue()); + reportIDFromMap = entry.getValue().toString().substring(1); + // The below line is used to optimize, so that if there is already same report id it wouldn't go through the whole process + similiarReportRuntime = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap); + if(similiarReportRuntime != null ) { + rrDashboardReports = (ReportRuntime) getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap).clone(); + intObj = getKey(reportsRuntimeMap,reportIDFromMap); + } else { + rrDashboardReports = rh.loadReportRuntime(request, reportIDFromMap, true, requestFlag); + } + if(entry.getValue().toString().toLowerCase().startsWith("c")) { + rrDashboardReports.setDisplayMode(ReportRuntime.DISPLAY_CHART_ONLY); + } else { + rrDashboardReports.setDisplayMode(ReportRuntime.DISPLAY_DATA_ONLY); + } + + downloadLimit = (rrDashboardReports.getMaxRowsInExcelDownload()>0)?rrDashboardReports.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + if (new Integer(nvl(rrDashboardReports.getDataContainerWidth(),"100")).intValue() >100) widthFlag = 1; + if (new Integer(nvl(rrDashboardReports.getDataContainerHeight(),"100")).intValue() >100) heightFlag = 1; + + if(record == 1) { + if(rrDashboardReports.getReportFormFields()!=null && rrDashboardReports.getReportFormFields().size()>0) { + buildReportdata = false; + if(rDisplayContent) buildReportdata = true; + } + } + + if(buildReportdata) { + if(similiarReportRuntime != null ) { + rd = (ReportData) reportDataMap.get(intObj); + ds = (DataSet) reportChartDataMap.get(intObj); + } else { + if (!rrDashboardReports.getReportType().equals(AppConstants.RT_HIVE)) + rd = rrDashboardReports.loadReportData(pageNo, userId, downloadLimit,request, false /*download*/); + else + rd = rrDashboardReports.loadHiveLinearReportData(rrDashboardReports.getReportSQL(), userId, 2,request); + ds = rrDashboardReports.loadChartData(userId,request); + } + } + + + long totalTime = System.currentTimeMillis() - currentTime; + formFields = AppUtils.getRequestNvlValue(request, "formFields"); + if(buildReportdata) { + rrDashboardReports.logReportRun(userId, String.valueOf(totalTime),formFields); + rrDashboardReports.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields); + } + + /*reportsRuntimeMap.put(new Integer(entry.getKey().toString()), rrDashboardReports); + reportDataMap.put(new Integer(entry.getKey().toString()), rd); + reportChartDataMap.put(new Integer(entry.getKey().toString()), ds); + reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1));*/ + + reportsRuntimeMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), rrDashboardReports); + reportDisplayTypeMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), entry.getValue().toString().substring(0,1)); + if(buildReportdata) { + reportDataMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), rd); + reportChartDataMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), ds); + } + + } + + /*if(widthFlag ==1) request.getSession().setAttribute("extendedWidth", "Y"); + else request.getSession().removeAttribute("extendedWidth"); + if(heightFlag ==1) request.getSession().setAttribute("extendedHeight", "Y"); + else request.getSession().removeAttribute("extendedHeight"); + */ + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP, new TreeMap(reportsRuntimeMap)); + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP, new TreeMap(reportDisplayTypeMap)); + if(buildReportdata) { + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP, new TreeMap(reportDataMap)); + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP, new TreeMap(reportChartDataMap)); + } +// debugLogger.debug("I am inside this if " + rr1.getReportType() + " "+rr1.getReportID()); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1); //changing session to request + //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1); + if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!= null || rr1.getReportType().equals(AppConstants.RT_DASHBOARD)) { + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME, rr1); + } + + return "raptor/report_dashboard_run_container.jsp"; + } else { + fromDashboard = AppUtils.getRequestFlag(request,"fromDashboard"); + if(isDashboardInDrillDownList(request)) fromDashboard= true; + + if(!fromDashboard) { + request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP); + request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); + request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REP_ID); + request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME); + request.getSession().removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP); + request.getSession().removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP); + } + //String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey"); + String report_email_sent_log_id = AppUtils.getRequestValue(request, "log_id"); + logger.debug(EELFLoggerDelegate.debugLogger, ("Email PDF" + pdfAttachmentKey+" "+ report_email_sent_log_id)); + + //email pdf attachment specific + if(nvl(pdfAttachmentKey).length()>0 && report_email_sent_log_id !=null) + isEmailAttachment = true; + if(isEmailAttachment) { + /* String query = "Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG" + + " where rownum = 1" + + " and gen_key='"+pdfAttachmentKey.trim()+"'" + + " and log_id ="+report_email_sent_log_id.trim() + + " and (sysdate - sent_date) < 1 ";*/ + + + String query = Globals.getDownloadAllEmailSent(); + query = query.replace("[pdfAttachmentKey.trim()]", pdfAttachmentKey.trim()); + query = query.replace("[report_email_sent_log_id.trim()]", report_email_sent_log_id.trim()); + + DataSet ds = DbUtils.executeQuery(query, 1); + if(!ds.isEmpty()) { + userId = ds.getString(0,"user_id"); + reportID = ds.getString(0, "rep_id"); + request.setAttribute("schedule_email_userId", userId); + } else { + request.setAttribute("message", "This link has expired, please login and regenerate the report"); + return "raptor/message.jsp"; + } + } else userId = AppUtils.getUserID(request); +// debugLogger.debug("Report ID b4 showbutton in ActionHandler " +// + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); +// debugLogger.debug("Report ID " + reportID + " " + reportIDFromSession); + + // Scheduling Dashoard report + if(reportID !=null && nvl(pdfAttachmentKey).length()>0) + rr = rh1.loadReportRuntime(request, reportID, true, 1); + if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD) && nvl(pdfAttachmentKey).length()>0) { + int DASH=7; + int requestFlag = DASH; + ReportHandler rh = new ReportHandler(); + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID); + //rr = null; + // get dashboard HTML from report runtime. getListOfReportsFromDashBoardHTML + String strHTML = rr.getDashboardLayoutHTML(); + //System.out.println("StrHTML " + strHTML); + // call getListOfReportsFromDashBoardHTML returns HashMap + + TreeMap treeMap = getListOfReportsFromDashBoardHTML(strHTML); + //System.out.println("Size " + hashMap.size()); + Set set = treeMap.entrySet(); + String value = ""; + + HashMap reportsRuntimeMap = new HashMap(); + HashMap reportDataMap = new HashMap(); + HashMap reportChartDataMap = new HashMap(); + HashMap reportDisplayTypeMap = new HashMap(); + + userId = null; + userId = AppUtils.getUserID(request); + int pageNo = -1; + int downloadLimit = 0; + int rep_idx = 0; + int widthFlag = 0; + int heightFlag = 0; + ReportRuntime rrDashboardReports = null; + Integer intObj = null; + ReportRuntime similiarReportRuntime = null; + rd = null; + DataSet ds = null; + String reportIDFromMap = null; + int record = 0; + boolean buildReportdata = true; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + record++; + Map.Entry entry = (Entry) iter.next(); + + reportIDFromMap = entry.getValue().toString().substring(1); + similiarReportRuntime = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap); + if(similiarReportRuntime != null ) { + rrDashboardReports = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap); + intObj = getKey(reportsRuntimeMap,reportIDFromMap); + } else { + rrDashboardReports = rh.loadReportRuntime(request, reportIDFromMap, true, requestFlag); + } + + downloadLimit = (rrDashboardReports.getMaxRowsInExcelDownload()>0)?rrDashboardReports.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + + if (new Integer(nvl(rrDashboardReports.getDataContainerWidth(),"100")).intValue() >100) widthFlag = 1; + if (new Integer(nvl(rrDashboardReports.getDataContainerHeight(),"100")).intValue() >100) heightFlag = 1; + if(record == 1) { + if(rrDashboardReports.getReportFormFields()!=null && rrDashboardReports.getReportFormFields().size()>0) { + buildReportdata = false; + if(rDisplayContent) buildReportdata = true; + } + } + if(buildReportdata) { + if(similiarReportRuntime != null ) { + rd = (ReportData) reportDataMap.get(intObj); + ds = (DataSet) reportChartDataMap.get(intObj); + } else { + + if (!rrDashboardReports.getReportType().equals(AppConstants.RT_HIVE)) + rd = rrDashboardReports.loadReportData(pageNo, userId, downloadLimit,request, false /*download*/); + else + rd = rrDashboardReports.loadHiveLinearReportData(rrDashboardReports.getReportSQL(), userId, 2,request); + ds = rrDashboardReports.loadChartData(userId,request); + } + } + + + + long totalTime = System.currentTimeMillis() - currentTime; + formFields = AppUtils.getRequestNvlValue(request, "formFields"); + + rrDashboardReports.logReportRun(userId, String.valueOf(totalTime),formFields); + rrDashboardReports.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields); + + reportsRuntimeMap.put(new Integer(entry.getKey().toString()), rrDashboardReports); + reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1)); + if(buildReportdata) { + reportDataMap.put(new Integer(entry.getKey().toString()), rd); + reportChartDataMap.put(new Integer(entry.getKey().toString()), ds); + //reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1)); + } + } + + /*if(widthFlag ==1) request.getSession().setAttribute("extendedWidth", "Y"); + else request.getSession().removeAttribute("extendedWidth"); + if(heightFlag ==1) request.getSession().setAttribute("extendedHeight", "Y"); + else request.getSession().removeAttribute("extendedHeight"); + */ + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP, new TreeMap(reportsRuntimeMap)); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); //changing session to request + if(buildReportdata) { + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP, new TreeMap(reportDisplayTypeMap)); + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP, new TreeMap(reportDataMap)); + request.getSession().setAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP, new TreeMap(reportChartDataMap)); + } + //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1); + //return nextPage; + } else { + + // Ends + + +// debugLogger.debug("Action Handler *****************" + new java.util.Date()+ " " + isGoBackAction); + ReportHandler rh = new ReportHandler(); + //rr = null; // COMMENT THIS LINE + boolean resetParams = AppUtils.getRequestFlag(request, + AppConstants.RI_RESET_PARAMS); + boolean resetAction = AppUtils.getRequestFlag(request, + AppConstants.RI_RESET_ACTION); + boolean refresh = false; + if (resetAction) { + rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + resetParams=true; + refresh = true; + if(rr!=null) { + rr.setParamValues(request, resetParams,refresh); + request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA); + rr.resetVisualSettings(); + } + return nextPage; + } + + /*if (isGoBackAction) { +// debugLogger.debug("Report back in action handler " + ((ReportRuntime) request.getSession().getAttribute( +// AppConstants.SI_REPORT_RUN_BACKUP))!=null?((ReportRuntime) request.getSession().getAttribute( +// AppConstants.SI_REPORT_RUN_BACKUP)).getReportID():((ReportRuntime) request.getSession().getAttribute( +// AppConstants.SI_REPORT_RUN_BACKUP))); + rr = null; + rr = getReportRuntimeFromBackup(request); + if (rr == null) + throw new Exception("[ActionHandler.reportRun] Report backup not found"); + reportID = rr.getReportID(); + } else {*/ + + logger.debug(EELFLoggerDelegate.debugLogger, ("Ocurring during Schedule ")); + //TODO differentiate Schedule with other actions +// if(isEmailAttachment) { +// +// } else { +// +// } + rr = rh.loadReportRuntime(request, reportID); + //setParamValues called for Drilldown to display formfield + //rr.setParamValues(request, false,true); + + //} // else + + ArrayList aL = (ArrayList)request.getSession().getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + ReportRuntime aLR = null; + if(aL != null) { +// for (int i = 1; i < aL.size(); i++) { +// aLR = (ReportRuntime) aL.get(i); +// if (!aLR.getReportID().equals(reportID)) { +// request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y"); +// } +// } +// if(reportID.equals(reportIDFromSession)) { + aLR = (ReportRuntime) aL.get(0); + if (aLR!=null && !aLR.getReportID().equals(reportID)) { + request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y"); + } +// } + } + + if(rDisplayContent) + rr.setDisplayFlags(true, true); + + if (rr.getDisplayContent()) { + int pageNo = 0; + if (isGoBackAction) + pageNo = rr.getCachedPageNo(); + else { + try { + pageNo = Integer.parseInt(AppUtils.getRequestNvlValue(request, AppConstants.RI_NEXT_PAGE)); + } catch (Exception e) { + } + + String vAction = AppUtils.getRequestNvlValue(request, + AppConstants.RI_VISUAL_ACTION); + String vCoId = AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID); + if (vAction.equals(AppConstants.VA_HIDE)) + rr.hideColVisual(vCoId); + else if (vAction.equals(AppConstants.VA_SHOW)) + rr.showColVisual(vCoId); + else if (vAction.equals(AppConstants.VA_SORT)) { + rr.sortColVisual(vCoId); + pageNo = 0; + } // else + } // else + + int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + if(isEmailAttachment) { + String limit = nvl(request.getParameter("download_limit"),"1000"); + downloadLimit = Integer.parseInt(limit); + } + //if (action.startsWith("mobile")) rr.setPageSize(5); + long reportTime = System.currentTimeMillis(); + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) + rd = rr.loadReportData(pageNo, userId, downloadLimit,request,false /*download*/); + else + rd = rr.loadHiveLinearReportData(rr.getReportSQL(), userId, 2,request); + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for the loading report data --- " + (System.currentTimeMillis() - reportTime))); + ReportData rd_whole = null; + boolean hideReportMap = rr.isDisplayOptionHideMap()||AppUtils.getRequestNvlValue(request, "noMap").equals("Y"); +/* if (Globals.getMapAllowedYN().equals("Y") && !hideReportMap && rr.getReportMap()!=null){ + rd_whole = rr.loadReportData(-1, userId, downloadLimit,request); + } +*/ + request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd); + //if (Globals.getMapAllowedYN().equals("Y") && !hideReportMap && (rr.getReportMap()!=null && rr.getReportMap().getLatColumn()!=null && rr.getReportMap().getLongColumn()!=null)) { + if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) { + String sql_whole = rr.getReportDataSQL(userId, downloadLimit, request); + request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole); + } else if(rr.getReportType().equals(AppConstants.RT_HIVE)) { + String sql_whole = rr.getReportSQL(); + request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole); + } + //} + //request.setAttribute(AppConstants.RI_REPORT_DATA_WHOLE, rd_whole); + // if(rr.getReportDataSize() > Globals.getFlatFileLowerLimit() && rr.getReportDataSize() <= Globals.getFlatFileUpperLimit() ) { + // rr.setFlatFileName(rh.saveFlatFile(request, rd, rr + // .getParamNameValuePairs(), rr.getReportName(), rr.getReportDescr())); + // } + //if(actionKey!=null && actionKey.equals("report.download")) { +// rr.setExcelPageFileName(rh.saveAsExcelFile(request, rd, rr +// .getParamNameValuePairs(), rr.getReportName(), rr.getReportDescr())); + //} + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) { + long currentChartTime = System.currentTimeMillis(); + DataSet chartDS = rr.loadChartData(userId,request); + if(chartDS != null) + request.getSession().setAttribute(AppConstants.RI_CHART_DATA, rr.loadChartData(userId,request)); + else + request.getSession().removeAttribute(AppConstants.RI_CHART_DATA); + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for the loading chart data --- " + (System.currentTimeMillis() - currentChartTime))); + } + +/* if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) { + request.getSession().setAttribute("FirstDashReport", rr); + } +*/ + } + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); //changing session to request + request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd); + } // else + long totalTime = System.currentTimeMillis() - currentTime; + formFields = AppUtils.getRequestNvlValue(request, "formFields"); + request.setAttribute(AppConstants.RLA_EXECUTION_TIME, "" + totalTime); + + + boolean isFromReportLog = AppUtils.getRequestFlag(request, "fromReportLog"); + if(!isFromReportLog) { + if(pdfAttachmentKey!=null && pdfAttachmentKey.length()>0) { + if(actionKey.equals("report.download")) { + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCEL, formFields); + } else if (actionKey.equals("report.download.pdf")) { + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_SCHEDULED_DOWNLOAD_PDF, formFields); + } + } else { + if(actionKey.equals("report.download") ) { + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_EXCEL, formFields); + } else if (actionKey.equals("report.download.pdf")) { + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_PDF, formFields); + } else if (actionKey.equals("report.csv.download")) { + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_CSV, formFields); + } else if (actionKey.equals("report.text.download")) { + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_TEXT, formFields); + } else { + + //rr.logReportRun(userId, String.valueOf(totalTime),formFields); + if(rd!=null && !action.equals("report.run.container")) + rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields); + } + } + } else { + rr.logReportExecutionTimeFromLogList(userId, String.valueOf(totalTime),formFields); + } + +/* if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) { + reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID); + ReportRuntime rrDash = rh1.loadReportRuntime(request, reportID, true, 1); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rrDash); + } +*/ + if(rr.isDrillDownURLInPopupPresent()) { + request.getSession().setAttribute("parent_"+rr.getReportID()+"_rr", rr); + request.getSession().setAttribute("parent_"+rr.getReportID()+"_rd", rd); + } + + if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + return "raptor/report_crosstab_run_container.jsp"; + } else if (rr.getReportType().equals(AppConstants.RT_HIVE) && !isEmailAttachment) { + return "raptor/report_hive_run_container.jsp"; + } + } // else + + boolean isEmbedded = false; + Object temp = request.getSession().getAttribute("isEmbedded"); + if(temp!=null){ + isEmbedded = (boolean)temp; + } + if(isEmbedded && !action.equals("chart.run")){ + HashMap embeddedReportsRuntimeMap = null; + HashMap embeddedReportsDataMap = null; + if(request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)!= null){ + embeddedReportsRuntimeMap = (HashMap)request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP); + } else { + embeddedReportsRuntimeMap = new HashMap(); + } + if(request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)!= null){ + embeddedReportsDataMap = (HashMap)request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP); + } else { + embeddedReportsDataMap = new HashMap(); + } + embeddedReportsRuntimeMap.put(rr.getReportID(), rr); + embeddedReportsDataMap.put(rr.getReportID(), rd); + + + request.getSession().setAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP, embeddedReportsRuntimeMap); + request.getSession().setAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP, embeddedReportsDataMap); + + } + + ReportJSONRuntime reportJSONRuntime = rr.createReportJSONRuntime(request, rd); + ObjectMapper mapper = new ObjectMapper(); + //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); + //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String jsonInString = ""; + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reportJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + + } + return jsonInString; + } catch (RaptorException e) { + try { + e.printStackTrace(); + + if(rr!=null) { // when user tries report they don't have access this should not throw exception that's why this if is added. + if(isEmailAttachment) + rr.logReportExecutionTime(userId, "", "Scheduled: " + AppConstants.RLA_ERROR, formFields); + else + rr.logReportExecutionTime(userId, "", "On Demand: " + AppConstants.RLA_ERROR, formFields); + } + + ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage(e.getMessage()); + errorJSONRuntime.setStacktrace(getStackTrace(e)); + ObjectMapper mapper = new ObjectMapper(); + //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); + //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String jsonInString = ""; + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + + } + return jsonInString; + + } catch (RaptorException ex) { + nextPage = (new ErrorHandler()).processFatalError(request, ex); + ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage(ex.getMessage()); + errorJSONRuntime.setStacktrace(getStackTrace(ex)); + ObjectMapper mapper = new ObjectMapper(); + //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); + //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String jsonInString = ""; + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } + return jsonInString; + } + //nextPage = (new ErrorHandler()).processFatalError(request, e); + } catch (Throwable t) { + t.printStackTrace(); + ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage(t.toString()); + errorJSONRuntime.setStacktrace(getStackTrace(t)); + ObjectMapper mapper = new ObjectMapper(); + //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); + //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String jsonInString = ""; + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + + } + return jsonInString; + + } + //return nextPage; + } // reportRun + + public static String getStackTrace(Throwable aThrowable) { + Writer result = new StringWriter(); + PrintWriter printWriter = new PrintWriter(result); + aThrowable.printStackTrace(printWriter); + return result.toString(); + } + + /** + * The below method is used to optimize, so that if there is already same report id in hashMap it wouldn't go through the whole process again. + **/ + private ReportRuntime getSimiliarReportRuntime(HashMap reportsRuntimeMap, String reportID) { + Set set = reportsRuntimeMap.entrySet(); + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + if (((ReportRuntime) entry.getValue()).getReportID().equals(reportID)) { + return (ReportRuntime) entry.getValue(); + } + } + return null; + } + + private Integer getKey(HashMap reportsRuntimeMap, String reportID) { + Set set = reportsRuntimeMap.entrySet(); + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + if (((ReportRuntime) entry.getValue()).getReportID().equals(reportID)) { + return new Integer(((String) entry.getKey()).substring(2)); + } + } + return null; + } + + public String reportSearch(HttpServletRequest request, String nextPage) { + return reportSearchExecute(request, nextPage); + } // reportSearch + + public String reportSearchUser(HttpServletRequest request, String nextPage) { + removeVariablesFromSession(request); + request.setAttribute(AppConstants.RI_USER_REPORTS, "Y"); + return reportSearchExecute(request, nextPage); + } // reportSearchUser + + public String reportSearchPublic(HttpServletRequest request, String nextPage) { + removeVariablesFromSession(request); + request.setAttribute(AppConstants.RI_PUBLIC_REPORTS, "Y"); + return reportSearchExecute(request, nextPage); + } // reportSearchPublic + + public String reportSearchFavorites(HttpServletRequest request, String nextPage) { + removeVariablesFromSession(request); + request.setAttribute(AppConstants.RI_FAVORITE_REPORTS, "Y"); + return reportSearchExecute(request, nextPage); + } // reportSearchFavorites + + public String reportSearchExecute(HttpServletRequest request, String nextPage) { + removeVariablesFromSession(request); + try { + SearchHandler sh = new SearchHandler(); + ReportSearchResultJSON sr = sh.loadReportSearchResult(request); + return sr.getJSONString(); + //request.setAttribute(AppConstants.RI_SEARCH_RESULT, sr); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportSearchExecute + + public String reportChartRun(HttpServletRequest request, String nextPage) { + ChartWebRuntime cwr = new ChartWebRuntime(); + return cwr.generateChart(request, false); //no data + } // reportSearchExecute + + public String reportChartDataRun(HttpServletRequest request, String nextPage) { + ChartWebRuntime cwr = new ChartWebRuntime(); + return cwr.generateChart(request); //data + } // reportSearchExecute + + + // public String reportRunExecute(HttpServletRequest request, String nextPage) { +// try { +// ReportRunHandler rh = new ReportRunHandler(); +// ReportRunResultJSON sr = rh.loadReportRunResult(request); +// return sr.getJSONString(); +// //request.setAttribute(AppConstants.RI_SEARCH_RESULT, sr); +// } catch (RaptorException e) { +// nextPage = (new ErrorHandler()).processFatalError(request, e); +// } +// +// return nextPage; +// } + + public String getQuickLinksJSON(HttpServletRequest request, String nextPage) { + String jsonInString = null; + try { + ArrayList quickLinks = ReportLoader.getQuickLinksJSON(request, request.getParameter("quick_links_menu_id"),true); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(quickLinks); + + } catch (Exception e) { + e.printStackTrace(); + } + return jsonInString; + } + + public String processScheduleReportList(HttpServletRequest request, String nextPage) { + String reportID = ""; + reportID = AppUtils.getRequestNvlValue(request, "schedule_reports"); + if (nvl(reportID).length()<=0) + reportID = AppUtils.getRequestNvlValue(request, AppConstants.RI_REPORT_ID); + // Added for form field chaining in schedule tab so that setParamValues() is called + request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y"); + + try { + boolean isAdmin = AppUtils.isAdminUser(request); + boolean check = ReportLoader.doesUserCanScheduleReport(request, null); + + logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^Check " + check + " Admin "+ isAdmin)); + + if(check || isAdmin) { + if(reportID.length()>0) { + ReportHandler rh = new ReportHandler(); + ReportDefinition rdef = rh.loadReportDefinition(request, reportID); + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + ReportSchedule reportSchedule = null; + if(rdef!=null) { + reportSchedule = new ReportSchedule(reportID, AppUtils.getUserID(request), false, request); + } + request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule); + } + } else { + //String message = "You have reached your schedule limit. Please visit this page again after removing your old schedules in \"My Schedule\" section."; + String message = "You have reached the scheduled report limit for your Login ID. Please remove any old schedule requests in the \"My Scheduled Reports\" screen before attempting to schedule any additional reports."; + nextPage = (new ErrorHandler()).processFatalError(request, new RaptorSchedularException(message)); + } + + } catch(Exception ex) { ex.printStackTrace();} + return nextPage; + } + + public String processSchedule(HttpServletRequest request, String nextPage) { + + // Added for form field chaining in schedule tab so that setParamValues() is called + + request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y"); + if(request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE)!=null && (!AppUtils.getRequestNvlValue(request, AppConstants.RI_ACTION).equals("report.schedule_only_from_search"))) { + String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION), + AppConstants.WA_BACK); + String scheduleID = ""; + scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID); + ReportSchedule reportSchedule = null; + + if( nvl(scheduleID).length() <= 0) { + reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE); + scheduleID = reportSchedule.getScheduleID(); + } + + String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + try { + boolean isAdmin = AppUtils.isAdminUser(request); + boolean check = ReportLoader.doesUserCanScheduleReport(request, scheduleID); + if(!isAdmin && !check) { + String message = "You have reached the scheduled report limit for your Login ID. Please remove any old schedule requests in the My Scheduled Reports screen before attempting to schedule any additional reports."; + nextPage = (new ErrorHandler()).processFatalError(request, new RaptorSchedularException(message)); + return nextPage; + } + + } catch (Exception ex) { ex.printStackTrace();} + if(reportSchedule == null) reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request); + String formFields = ""; + formFields = reportSchedule.getFormFields(); + formFields = (formFields.length()>1)?formFields.substring(1):formFields; + String formFieldsArr[] = formFields.split("&"); + String sessionParams[] = Globals.getSessionParamsForScheduling().split(","); + + for (int i=0; i1)?formFields.substring(1):formFields; + String formFieldsArr[] = formFields.split("&"); + String sessionParams[] = Globals.getSessionParamsForScheduling().split(","); + + for (int i=0; i 0) + ws.performGoToStep(goToStep); + else + ws.performAction(action, rdef); + } catch (ValidationException ve) { + (new ErrorHandler()).processError(request, ve); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } catch (Throwable t) { + t.printStackTrace(); + } + + return nextPage; + } // reportWizard + + public String refreshCache ( HttpServletRequest request, String nextPage ) { + //DataCache.refreshReportTableSources(); + removeVariablesFromSession(request); + DataCache.refreshAll(); + Globals.getAppUtils().resetUserCache(); + request.setAttribute("message", "Cache Refreshed"); + return nextPage; + } + public String reportCreate(HttpServletRequest request, String nextPage) { + try { + removeVariablesFromSession(request); + ReportDefinition rdef = ReportDefinition.createBlank(request); + + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + // request.setAttribute(AppConstants.RI_CUR_STEP, + // AppConstants.WS_DEFINITION); + DataCache.refreshReportTableSources(); + request.getSession().removeAttribute("remoteDB"); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportCreate + + public String reportImportSave(HttpServletRequest request, String nextPage) { + try { + String reportXML = nvl(AppUtils.getRequestValue(request, "reportXML")).trim(); + + ReportHandler rh = new ReportHandler(); + ReportDefinition rdef = rh.createReportDefinition(request, "-1", reportXML); + rdef.updateReportDefType(); + rdef.generateWizardSequence(request); + rdef.setReportName("Import: " + rdef.getReportName()); + rdef.clearAllDrillDowns(); + + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + } catch (RaptorException e) { + request.setAttribute("error_extra_msg", "Unable to parse XML. Nested error: "); + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportImportSave + + private String reportLoad(HttpServletRequest request, String nextPage, boolean asCopy) { + try { + String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + + ReportHandler rh = new ReportHandler(); + ReportDefinition rdef = rh.loadReportDefinition(request, reportID); + if (asCopy) + rdef.setAsCopy(request); + else + rdef.checkUserWriteAccess(request); + + rdef.getWizardSequence().performGoToStep(AppConstants.WS_DEFINITION); + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + // request.setAttribute(AppConstants.RI_CUR_STEP, + // AppConstants.WS_DEFINITION); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportLoad + + public String reportCopy(HttpServletRequest request, String nextPage) { + return reportLoad(request, nextPage, true); + } // reportCopy + + public String reportEdit(HttpServletRequest request, String nextPage) { + return reportLoad(request, nextPage, false); + } // reportEdit + + public String reportDelete(HttpServletRequest request, String nextPage) { + try { + String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + try { + int i = Integer.parseInt(reportID); + } catch(NumberFormatException ex) { + throw new UserDefinedException("Not a valid report id"); + } + String userID = AppUtils.getUserID(request); + + (new ReportSecurity(reportID)).checkUserDeleteAccess(request); + + ReportLoader.deleteReportRecord(reportID); + + return "{\"deleted\":true}"; + //nextPage = reportSearchExecute(request, nextPage); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + //return nextPage; + return "{\"deleted\":false}"; + } // reportDelete + + private String generateSearchString(HttpServletRequest request) { + String searchString = AppUtils.getRequestNvlValue(request, AppConstants.RI_SEARCH_STRING); + boolean containFlag = AppUtils.getRequestFlag(request, AppConstants.RI_CONTAIN_FLAG); + return (searchString.length() > 0) ? ((containFlag ? "%" : "") + searchString + "%"):""; + } // generateSearchString + + public String reportFormFieldPopup(HttpServletRequest request, String nextPage) { + try { + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + + FormField ff = rr.getFormField(request.getParameter(AppConstants.RI_FIELD_NAME)); + ReportFormFields rff = rr.getReportFormFields(); + + int idx = 0; + FormField ff1 = null; + Map fieldNameMap = new HashMap(); + int countOfFields = 0 ; + String userId = AppUtils.getUserID(request); + IdNameList lookup = ff.getLookupList(); + String oldSQL = lookup.getOldSql(); + + if(AppUtils.getRequestFlag(request, AppConstants.RI_TEXTFIELD_POP)) { + for(rff.resetNext(); rff.hasNext(); idx++) { + ff1 = rff.getNext(); + fieldNameMap.put(ff1.getFieldName(), ff1.getFieldDisplayName()); + countOfFields++; + } + + + //List formParameter = new ArrayList(); + String formField = ""; + HashMap valuesMap = new HashMap(); + for(int i = 0 ; i < rff.size(); i++) { + formField = ((FormField)rff.getFormField(i)).getFieldName(); + if(request.getParameterValues(formField) != null && request.getParameterValues(formField).length > 1 ) { + String[] vals = (String[]) request.getParameterValues(formField); + String value = ""; + StringBuffer valueBuf = new StringBuffer(); + for(int ii = 0 ; ii < vals.length; ii++) { + if(ii == 0) valueBuf.append("("); + valueBuf.append(vals[ii]); + if(ii == vals.length-1) valueBuf.append(")"); + else valueBuf.append(","); + } + value = valueBuf.toString(); + valuesMap.put(fieldNameMap.get(formField), value); + } else if(request.getParameter(formField) != null) { + valuesMap.put(fieldNameMap.get(formField), request.getParameter(formField)); + } + } + if(countOfFields != 0) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = (oldSQL==null)?lu.getSql():oldSQL; + oldSQL = SQL; + Set set = valuesMap.entrySet(); + String value = ""; + StringBuffer valueBuf = new StringBuffer(); + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + if(entry.getValue() instanceof String[]) { + String[] vals = (String[]) entry.getValue(); + for(int i = 0 ; i < vals.length; i++) { + if(i == 0) valueBuf.append("("); + valueBuf.append(vals[i]); + if(i == vals.length-1) valueBuf.append(")"); + else valueBuf.append(","); + } + value = valueBuf.toString(); + } else { + value = (String) entry.getValue(); + } + // added so empty string would be treated as null value if not given in single quotes. + if(value==null || value.trim().length()<=0) value="NULL"; + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", Utils.oracleSafe(value)); + } + if(request.getParameter(ff.getFieldName())!=null) { + lookup = new IdNameSql(-1,SQL,null); + lookup.setOldSql(oldSQL); + } + else { + lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); + lookup.setOldSql(oldSQL); + } + //lookup.loadData("0"); + } + if(lookup instanceof IdNameSql) ((IdNameSql)lookup).setDataSizeUsedinPopup(-3); // -3 indicates to run the count sql for pagination. + } + if(lookup instanceof IdNameSql) { + ((IdNameSql)lookup).loadUserData(request.getParameter(AppConstants.RI_NEXT_PAGE), + nvl(generateSearchString(request),"%"), rr.getDBInfo(),userId); + } + + int dataSizeForPopUp = 0; + if(lookup instanceof IdNameSql) { + dataSizeForPopUp = ((IdNameSql)lookup).getDataSizeUsedinPopup(); + } else + dataSizeForPopUp = lookup.getDataSize(); + + ff.setLookupList(lookup); + request.setAttribute("lookupList", lookup); + if(dataSizeForPopUp >= 0) + request.getSession().setAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP, ""+dataSizeForPopUp); + } catch (RaptorException e) { + e.printStackTrace(); + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + return nextPage; + } // reportFormFieldPopup + + public String reportValuesMapDefPopup(HttpServletRequest request, String nextPage) { + try { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String colName = AppUtils.getRequestNvlValue(request, "colName"); + String colType = nvl(AppUtils.getRequestValue(request, "colType"), + AppConstants.CT_CHAR); + String displayName = AppUtils.getRequestNvlValue(request, "displayName"); + String displayFormat = AppUtils.getRequestNvlValue(request, "displayFormat"); + String tableId = AppUtils.getRequestNvlValue(request, "tableId"); + String dbInfo = rdef.getDBInfo(); + if (Utils.isNull(dbInfo)) { + dbInfo = (String) request.getSession().getAttribute("remoteDB"); + } + /*String query = "SELECT x FROM (SELECT DISTINCT " + + (colType.equals(AppConstants.CT_DATE) ? ("TO_CHAR(" + colName + ", '" + + nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT) + "')") + : colName) + " x FROM " + + rdef.getTableById(tableId).getTableName() + " WHERE " + colName + + " IS NOT NULL ORDER BY 1) xx WHERE ROWNUM <= " + + Globals.getDefaultPageSize();*/ + + + String q1 = Globals.getReportValuesMapDefA(); + + String q2 = Globals.getReportValuesMapDefB(); + q2 = q2.replace("[colName]", colName); + q2 = q2.replace("[nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT)]", nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT)); + + String q3 = Globals.getReportValuesMapDefC(); + q3 = q3.replace("[colName]", colName); + + String q4 = Globals.getReportValuesMapDefD(); + q4 = q4.replace("[rdef.getTableById(tableId).getTableName()]", rdef.getTableById(tableId).getTableName()); + q4 = q4.replace("[colName]", colName); + q4 = q4.replace("[Globals.getDefaultPageSize()]", String.valueOf(Globals.getDefaultPageSize())); + + String query = q1 + (colType.equals(AppConstants.CT_DATE) ? q2 : q3) + q4; + + DataSet ds = ConnectionUtils.getDataSet(query, dbInfo); + request.setAttribute(AppConstants.RI_DATA_SET, ds); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportValuesMapDefPopup + + public String reportDrillDownToReportDefPopup(HttpServletRequest request, String nextPage) { + try { + // ReportDefinition rdef = (ReportDefinition) + // request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); + String ddReportID = AppUtils + .getRequestNvlValue(request, AppConstants.RI_REPORT_ID); + ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, ddReportID, + false); + if (ddRr != null) + request.setAttribute(AppConstants.RI_FORM_FIELDS, ddRr.getReportFormFields()); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportDrillDownToReportDefPopup + + public String reportFilterDataPopup(HttpServletRequest request, String nextPage) { + try { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String colId = AppUtils.getRequestNvlValue(request, AppConstants.RI_COLUMN_ID); + IdNameColLookup lookup = null; + String dbInfo = rdef.getDBInfo(); + if (Utils.isNull(dbInfo)) { + dbInfo = (String) request.getSession().getAttribute("remoteDB"); + } + if (!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_PARAMS)) + lookup = (IdNameColLookup) request.getSession().getAttribute( + AppConstants.SI_COLUMN_LOOKUP); + if (lookup == null || (!colId.equals(lookup.getColId()))) { + DataColumnType dct = rdef.getColumnById(colId); + lookup = new IdNameColLookup(colId, rdef.getTableById(dct.getTableId()) + .getTableName(), dct.getColName(), rdef.getSelectExpr(dct), dct + .getColName() + + (dct.getColType().equals(AppConstants.CT_DATE) ? " DESC" : "")); + request.getSession().setAttribute(AppConstants.SI_COLUMN_LOOKUP, lookup); + } // if + + lookup.loadData(nvl(request.getParameter(AppConstants.RI_NEXT_PAGE), "0"), + generateSearchString(request), dbInfo); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportFilterDataPopup + + public String reportShowSQLPopup(HttpServletRequest request, String nextPage) { + try { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + String reportSQL = rdef.generateSQL(AppUtils.getUserID(request),request); + + String[] sqlClause = { "SELECT ", "FROM ", "WHERE ", "GROUP BY ", "HAVING ", + "ORDER BY " }; + + int idxNext = 0; + StringBuffer sb = new StringBuffer(); + while (idxNext < sqlClause.length) { + sb.append(""); + if (idxNext > 0) + sb.append("    "); + sb.append(sqlClause[idxNext]); + sb.append("
\n"); + + int clauseStartPos = reportSQL.indexOf(sqlClause[idxNext]) + + sqlClause[idxNext].length(); + do + idxNext++; + while ((idxNext < sqlClause.length) + && (reportSQL.indexOf(sqlClause[idxNext]) < 0)); + + String clauseContent = null; + if (idxNext < sqlClause.length) + clauseContent = reportSQL.substring(clauseStartPos, reportSQL + .indexOf(sqlClause[idxNext]) - 1); + else + clauseContent = reportSQL.substring(clauseStartPos); + + while (clauseContent.length() > 0) { + int braketCount = 0; + StringBuffer nextToken = new StringBuffer(); + for (int i = 0; i < clauseContent.length(); i++) { + char ch = clauseContent.charAt(i); + nextToken.append(ch); + if (ch == '(') + braketCount++; + else if (ch == ')') + braketCount--; + else if (ch == ',') + if (braketCount == 0) + break; + } // for %> + + sb.append("        "); + sb.append(nextToken.toString()); + sb.append("
\n"); + + if (nextToken.length() < clauseContent.length()) + clauseContent = clauseContent.substring(nextToken.length() + 1); + else + clauseContent = ""; + } // while + } // while + + request.setAttribute(AppConstants.RI_FORMATTED_SQL, sb.toString()); + request.setAttribute(AppConstants.RI_PAGE_TITLE, "Generated SQL"); + request.setAttribute(AppConstants.RI_PAGE_SUBTITLE, "Generated SQL for report " + + rdef.getReportName()); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // reportShowSQLPopup + + public String testSchedCondPopup(HttpServletRequest request, String nextPage) { + try { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String sql = AppUtils.getRequestNvlValue(request, AppConstants.RI_FORMATTED_SQL); + + request.setAttribute("msg_align", " align=center"); + request.setAttribute(AppConstants.RI_PAGE_TITLE, "Test Scheduler Condition"); + // request.setAttribute(AppConstants.RI_PAGE_SUBTITLE, ...); + //String query = "SELECT 1 FROM DUAL WHERE EXISTS (" + sql + ")"; + + String query = Globals.getTestSchedCondPopup(); + query = query.replace("[sql]", sql); + + DataSet ds = null; + String remoteDb = request.getParameter("remoteDbPrefix"); + String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb + : rdef.getDBInfo(); + ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix); + // if ( (remoteDbPrefix!=null) && + // (!remoteDbPrefix.equals(AppConstants.DB_LOCAL))) { + // Globals.getRDbUtils().setDBPrefix(remoteDbPrefix); + // ds = RemDbUtils.executeQuery(query); + // } + // else + // ds = DbUtils.executeQuery(query); + if (ds.getRowCount() == 0) + request + .setAttribute(AppConstants.RI_FORMATTED_SQL, + "
Condition NOT satisfied - email notification will NOT be send.

"); + else + request + .setAttribute(AppConstants.RI_FORMATTED_SQL, + "
Condition satisfied - email notification will be send.

"); + } catch (Exception e) { + // nextPage = (new ErrorHandler()).processFatalError(request, e); + request.setAttribute(AppConstants.RI_FORMATTED_SQL, "
SQL ERROR " + + e.getMessage() + "
Email notification will NOT be send.

"); + } + + return nextPage; + } // testSchedCondPopup + + public String testRunSQLPopup(HttpServletRequest request, String nextPage) { + String sql = AppUtils.getRequestNvlValue(request, AppConstants.RI_FORMATTED_SQL); + if(nvl(sql).length()<=0) { + sql = AppUtils.getRequestNvlValue(request, "reportSQL"); + } + + + boolean chkFormFieldSQL = AppUtils.getRequestNvlValue(request, + AppConstants.RI_CHK_FIELD_SQL).equals("Y"); + try { + if (!sql.trim().toUpperCase().startsWith("SELECT")) + throw new UserDefinedException( + "Invalid statement - the SQL must start with the keyword SELECT"); + + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + if (!chkFormFieldSQL) { + if (rdef.getFormFieldList() != null) + for (Iterator iter = rdef.getFormFieldList().getFormField().iterator(); iter + .hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = rdef.getFormFieldDisplayName(fft); + /* + * if(paramValues.isParameterMultiValue(fieldId)) + * generatedSQL = Utils.replaceInString(generatedSQL, + * fieldDisplay, nvl(formatListValue((String) + * paramValues.get(fieldId), null, false, false, null), + * "NULL")); else + */ + sql = Utils.replaceInString(sql, fieldDisplay, "NULL"); + } // for + } // if + DataSet ds = null; + String remoteDb = request.getParameter("remoteDbPrefix"); + String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb + : rdef.getDBInfo(); + String userId = AppUtils.getUserID(request); + sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId); + String[] reqParameters = Globals.getRequestParams().split(","); + String[] sessionParameters = Globals.getSessionParams().split(","); + javax.servlet.http.HttpSession session = request.getSession(); + logger.debug(EELFLoggerDelegate.debugLogger, ("B4 testRunSQL " + sql)); + if(request != null ) { + for (int i = 0; i < reqParameters.length; i++) { + if(!reqParameters[i].startsWith("ff")) + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) ); + else + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) ); + } + } + if(session != null ) { + for (int i = 0; i < sessionParameters.length; i++) { + //if(!sessionParameters[i].startsWith("ff")) + //sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); + //else { + logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]))); + sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + //} + } + } + logger.debug(EELFLoggerDelegate.debugLogger, ("After testRunSQL " + sql)); + + ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix, true); + // if ( (remoteDbPrefix!=null) && + // (!remoteDbPrefix.equals(AppConstants.DB_LOCAL))) { + // Globals.getRDbUtils().setDBPrefix(remoteDbPrefix); + // ds = RemDbUtils.executeQuery(sql, + // Globals.getDefaultPageSize()+1); + // } + // else + // ds = DbUtils.executeQuery(sql, Globals.getDefaultPageSize()+1); + if (chkFormFieldSQL && ds.getRowCount() > 0) { + String id = ds.getString(0, "id"); + String name = ds.getString(0, "name"); + } // if + + request.setAttribute(AppConstants.RI_DATA_SET, ds); + } catch (RaptorException e) { + request.setAttribute(AppConstants.RI_EXCEPTION, e); + } + + return nextPage; + } // testRunSQLPopup + + public String importSemaphorePopup(HttpServletRequest request, String nextPage) { + try { + (new WizardProcessor()).processImportSemaphorePopup(request); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // importSemaphorePopup + + public String saveSemaphorePopup(HttpServletRequest request, String nextPage) { + try { + (new WizardProcessor()).processSemaphorePopup(request); + } catch (RaptorException e) { + nextPage = (new ErrorHandler()).processFatalError(request, e); + } + + return nextPage; + } // saveSemaphorePopup + + public String gotoJsp(HttpServletRequest request, String nextPage) { + return nextPage; + } // gotoJsp + + public String downloadAll(HttpServletRequest request, String nextPage) throws InterruptedException, IOException, Exception { + String emailId = null; + String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey"); + boolean isFromSchedule = nvl(pdfAttachmentKey).length()>0; + if(!isFromSchedule) + emailId = AppUtils.getUserEmail(request); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd"); + java.util.Date currDate = new java.util.Date(); + String timestamp = sdf.format(currDate); + String dateStr = sdf1.format(currDate); + + String userId = null; + if(!isFromSchedule) + userId = AppUtils.getUserID(request); + else + userId = AppUtils.getRequestValue(request, "user_id"); + Runtime runtime = Runtime.getRuntime(); + ReportRuntime rr = null; + if(!isFromSchedule) { + rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + if(rr!=null) AppUtils.getUserEmail(request); + } + String scheduleId = ""; + + if(isFromSchedule) { + String reportID = null; + String report_email_sent_log_id = AppUtils.getRequestValue(request, "log_id"); + /*String query = "Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG" + + " where rownum = 1" + + " and gen_key='"+pdfAttachmentKey.trim()+"'" + + " and log_id ="+report_email_sent_log_id.trim() + + " and (sysdate - sent_date) < 1 ";*/ + + String query = Globals.getDownloadAllEmailSent(); + query = query.replace("[pdfAttachmentKey.trim()]", pdfAttachmentKey.trim()); + query = query.replace("[report_email_sent_log_id.trim()]", report_email_sent_log_id.trim()); + + DataSet ds = DbUtils.executeQuery(query, 1); + if(!ds.isEmpty()) { + userId = ds.getString(0,"user_id"); + reportID = ds.getString(0, "rep_id"); + request.setAttribute("schedule_email_userId", userId); + } else { + request.setAttribute("message", "This link has expired, please login and regenerate the report"); + return "raptor/message.jsp"; + } + + ReportHandler rh1 = new ReportHandler(); + + if(reportID !=null && nvl(pdfAttachmentKey).length()>0) { + rr = rh1.loadReportRuntime(request, reportID, true, 1); + rr.loadReportData(-1, userId, 1000 ,request, false /*download*/); + } + + String d_sql = Globals.getDownloadAllGenKey(); + d_sql = d_sql.replace("[pdfAttachmentKey]", pdfAttachmentKey); + + //ds = DbUtils.executeQuery("select schedule_id from cr_report_email_sent_log u where U.GEN_KEY = '"+ pdfAttachmentKey + "'"); + + ds = DbUtils.executeQuery(d_sql); + for (int i = 0; i < ds.getRowCount(); i++) { + scheduleId = ds.getString(i,0); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, ("SQL2:\n"+ rr.getCachedSQL())); + String fileName = rr.getReportID()+"_"+userId+"_"+timestamp; + boolean flag = false; + logger.debug(EELFLoggerDelegate.debugLogger, (""+Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr))); + // if(Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr)) { + // flag = true; + // } + + if(flag){ + String strFileName = Utils.getLatestDownloadableFile(rr.getReportID()+"_"+userId+"_"+dateStr); + //debugLogger.debug("File Name " + strFileName); + StringBuffer messageBuffer = new StringBuffer(""); + messageBuffer.append("Download data file using the following link
"); + messageBuffer.append("click here.

"); + request.setAttribute("message", messageBuffer.toString()); + } + else if(!flag) { + String whole_fileName = (Globals.getShellScriptDir() +AppConstants.SHELL_QUERY_DIR+ fileName+AppConstants.FT_SQL); + String whole_columnsfileName = (Globals.getShellScriptDir() +AppConstants.SHELL_QUERY_DIR+ fileName+AppConstants.FT_COLUMNS); + + logger.debug(EELFLoggerDelegate.debugLogger, ("FILENAME "+whole_fileName)); + + List l = rr.getAllColumns(); + StringBuffer allColumnsBuffer = new StringBuffer(); + DataColumnType dct = null; + + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + allColumnsBuffer.append(dct.getDisplayName()); + if(iter.hasNext()) + allColumnsBuffer.append("|"); + } + try { + PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(whole_columnsfileName)))); + xmlOut.println(allColumnsBuffer.toString()); + xmlOut.flush(); + xmlOut.close(); + } catch (IOException e) {e.printStackTrace();} + try { + PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(whole_fileName)))); + logger.debug(EELFLoggerDelegate.debugLogger, ("**************************")); + logger.debug(EELFLoggerDelegate.debugLogger, (rr.getWholeSQL())); + logger.debug(EELFLoggerDelegate.debugLogger, ("************************")); + logger.debug(EELFLoggerDelegate.debugLogger, ("************************")); + logger.debug(EELFLoggerDelegate.debugLogger, (rr.parseReportSQL(rr.getWholeSQL()))); + xmlOut.println(rr.parseReportSQL(rr.getWholeSQL())); + //xmlOut.println("******************"); + //xmlOut.println(rr.getWholeSQL()); + xmlOut.flush(); + xmlOut.close(); + } catch (IOException e) {e.printStackTrace();} + + StringBuffer command = new StringBuffer(Globals.getShellScriptDir() + AppConstants.SHELL_SCRIPTS_DIR); + if(nvl(emailId).length()>0) { + command.append(AppConstants.SHELL_SCRIPT_NAME + " " + (fileName+AppConstants.FT_SQL)); + command.append(" "+emailId); + } + else if (nvl(scheduleId).length()>0) { + command.append(AppConstants.SCHEDULE_SHELL_SCRIPT_NAME + " " + (fileName+AppConstants.FT_SQL)); + command.append(" " + scheduleId); + } + logger.debug(EELFLoggerDelegate.debugLogger, ("Command " + command)); + Process downloadProcess = runtime.exec(command.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, ("Command Executed ")); + //Connection connection = DbUtils.getConnection(); + Enumeration enum1 = rr.getParamKeys(); + String value = "", key = ""; + String paramStr = ""; + StringBuffer paramBuffer = new StringBuffer(); + if(enum1!=null) { + for (; enum1.hasMoreElements();) { + key = (String) enum1.nextElement(); + value = rr.getParamValue(key); + paramBuffer.append(key+":"+value+" "); + } + paramStr = paramBuffer.toString(); + } + + StringBuffer retrieveUserEmailQry = null; + ArrayList userEmailList = new ArrayList(); + if(nvl(scheduleId).length()>0) { + /*retrieveUserEmailQry = new StringBuffer(); + retrieveUserEmailQry.append(" SELECT "); + retrieveUserEmailQry.append(" au.user_id "); + retrieveUserEmailQry.append(" FROM "); + retrieveUserEmailQry.append(" (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.run_date IS NOT NULL "); + retrieveUserEmailQry.append(" AND rs.schedule_id = " + scheduleId + " ) x, cr_report r, app_user au "); + retrieveUserEmailQry.append(" WHERE "); + retrieveUserEmailQry.append("x.rep_id = r.rep_id "); + retrieveUserEmailQry.append(" AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = " + scheduleId ); + retrieveUserEmailQry.append(" UNION "); + retrieveUserEmailQry.append(" SELECT ur.user_id FROM fn_user_role ur "); + retrieveUserEmailQry.append(" WHERE ur.role_id IN "); + retrieveUserEmailQry.append(" (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 "); + retrieveUserEmailQry.append(" WHERE rsu2.schedule_id = x.schedule_id and "); + retrieveUserEmailQry.append(" rsu2.schedule_id = "+ scheduleId + ")) ");*/ + + String r_sql = Globals.getDownloadAllRetrieve(); + r_sql = r_sql.replace("[scheduleId]", scheduleId); + + // DataSet ds = DbUtils.executeQuery(retrieveUserEmailQry.toString()); + DataSet ds = DbUtils.executeQuery(r_sql); + + for (int i = 0; i < ds.getRowCount(); i++) { + userEmailList.add(ds.getString(i, 0)); + } + + } + // String insertQry = "insert into cr_report_dwnld_log (user_id,rep_id,file_name,dwnld_start_time,filter_params) values (?,?,?,?,?)"; + String insertQry = Globals.getDownloadAllInsert(); + + + Connection connection = null; + PreparedStatement pst = null; + try { + connection = DbUtils.getConnection(); + pst = connection.prepareStatement(insertQry); + if(nvl(emailId).length()>0){ + pst.setInt(1, Integer.parseInt(userId)); + pst.setInt(2, Integer.parseInt(rr.getReportID())); + pst.setString(3, fileName+AppConstants.FT_ZIP); + pst.setTimestamp(4,new java.sql.Timestamp(currDate.getTime())); + pst.setString(5,paramStr); + pst.execute(); + connection.commit(); + } else { + for (int i = 0; i < userEmailList.size(); i++) { + pst.setInt(1, Integer.parseInt((String)userEmailList.get(i))); + pst.setInt(2, Integer.parseInt(rr.getReportID())); + pst.setString(3, fileName+AppConstants.FT_ZIP); + pst.setTimestamp(4,new java.sql.Timestamp(currDate.getTime())); + pst.setString(5,paramStr); + pst.execute(); + connection.commit(); + } + } + pst.close(); + connection.close(); + logger.debug(EELFLoggerDelegate.debugLogger, ("Data inserted")); + } catch (SQLException ex) { + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + throw new RaptorException (ex); + } finally { + try { + if(connection!=null) + connection.close(); + if(pst!=null) + pst.close(); + } catch (SQLException ex) { + throw new RaptorException(ex); + } + } + //DbUtils.commitTransaction(connection); + //DbUtils.clearConnection(connection); + + + +// debugLogger.debug("|"+downloadProcess.toString() + "|"); +// if (downloadProcess == null) +// throw new Exception("unable to create a process for command:" + +// command); +// int retCode= 1; +// try { +// retCode= downloadProcess.waitFor(); +// } catch (InterruptedException e){ +// e.printStackTrace(); +// } +// debugLogger.debug("retCode " + retCode); +// Process child = rtime.exec("/bin/bash"); +// BufferedWriter outCommand = new BufferedWriter(new +// OutputStreamWriter(child.getOutputStream())); +// outCommand.write(Globals.getShellScriptName()); +// outCommand.flush(); +// int retCode = child.waitFor(); +// debugLogger.debug("RetCode " + retCode); + //request.setAttribute("message", "Shell Script is running in the background. You'll get an email once it is done"); + } + + return nextPage; + } + public String getChildDropDown(HttpServletRequest request, String nextPage) throws RaptorRuntimeException { + + if(request.getParameter("firstTime") != null) { return nextPage; } + + /*ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + + String c_master = request.getParameter("c_master"); + java.util.HashMap valuesMap = Globals.getRequestParamtersMap(request); + request.setAttribute("c_master", c_master); + + int idx = 0; + ReportFormFields rff = rr.getReportFormFields(); + FormField ff = null; + for(rff.resetNext(); rff.hasNext(); idx++) { + ff = rff.getNext(); + + + if(ff.getDependsOn() != null && ff.getDependsOn().trim() != "") + { + String val = request.getParameter(ff.getFieldName()); + request.setAttribute(ff.getFieldName(), ff.getHtml(val, valuesMap, rr)); + } + + } + */ + return nextPage; + + } + + private void removeVariablesFromSession(HttpServletRequest request) { + HttpSession session = request.getSession(); + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + session.removeAttribute(AppConstants.DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID); + session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); + session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP); + session.removeAttribute(AppConstants.SI_MAP); + session.removeAttribute(AppConstants.SI_MAP_OBJECT); + session.removeAttribute(AppConstants.SI_REPORT_DEFINITION); + session.removeAttribute(AppConstants.SI_REPORT_RUNTIME); + session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP); + session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE); + session.removeAttribute(AppConstants.RI_REPORT_DATA); + session.removeAttribute(AppConstants.RI_CHART_DATA); + session.removeAttribute(AppConstants.SI_FORMFIELD_INFO); + session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + session.removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP); + session.removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP); + Enumeration enum1 = session.getAttributeNames(); + String attributeName = ""; + while(enum1.hasMoreElements()) { + attributeName = enum1.nextElement(); + if(attributeName.startsWith("parent_")) { + session.removeAttribute(attributeName); + } + } + } + + + private TreeMap getListOfReportsFromDashBoardHTML(String htmlString) { + //String sourcestring = "
[Report#123][Report#124]
[Report#125][Report#126]
"; + String sourcestring = htmlString; + //Pattern re = Pattern.compile("([a-z]+)\\[([a-z]+)([=<>]+)([a-z]+)\\]",Pattern.CASE_INSENSITIVE); + //Pattern re = Pattern.compile("\\[([R][e][p][o][r][t][#])[(*)]\\]"); + Pattern re = Pattern.compile("\\[(.*?)\\]"); //\\[(.*?)\\] + Matcher m = re.matcher(sourcestring); + HashMap hashReports = new HashMap(); + int mIdx = 0; + while (m.find()){ + for( int groupIdx = 0; groupIdx < m.groupCount(); groupIdx++ ){ + String str = m.group(groupIdx); + //System.out.println(str); + hashReports.put(new String(Integer.toString(mIdx+1)), (str.substring(1).toLowerCase().startsWith("chart")?"c":"d") + str.substring(str.indexOf("#")+1, str.length()-1)); + } + mIdx++; + } + // Sorting HashMap based on Keys + /*List mapKeys = new ArrayList(hashReports.keySet()); + List mapValues = new ArrayList(hashReports.values()); + hashReports.clear(); + hashReports = null; + hashReports = new HashMap(); + + TreeSet sortedSet = new TreeSet(mapKeys); + Object[] sortedArray = sortedSet.toArray(); + int size = sortedArray.length; + for (int i=0; i iter = reportCols.iterator(); iter.hasNext();) { + + DataColumnType dc = (DataColumnType) iter.next(); + if (colNames.length() > 0) + colNames.append(", "); + colNames.append(dc.getColId()); + if (dc.isVisible()) { + //TODO: Drilldown URL + //sql = reportRuntime.parseReportSQLForDrillDownParams(sql, dc, request); + } + } + + DataSet ds = null; + // try { + String dbInfo = reportRuntime.getDBInfo(); + if(maxRows == 1) + sql += " limit "+ maxRows; + System.out.println("SQL getReportData()- " + sql); + ds = ConnectionUtils.getDataSet(sql, dbInfo); + int totalRows = 0; + /*if (reportRuntime.getReportDataSize() < 0) {*/ + //String countSQL = "SELECT count(*) FROM (" + sql + ") x"; + String dbType = ""; + + if (dbInfo!=null && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + + totalRows = ds.getRowCount(); + /*}*/ + ReportData rd = new ReportData(0, true); + + if(totalRows > 0) { + // Already defined changed for modifying request parameters + //List reportCols = getAllColumns(); + Vector visibleCols = new Vector(reportCols.size()); + Vector formatProcessors = new Vector(reportCols.size()); + + // ColumnHeaderRow chr = new ColumnHeaderRow(); + // rd.reportColumnHeaderRows.addColumnHeaderRow(chr); + // chr.setRowHeight("30"); + int count =0 ; + + /* ADDED */ + ReportFormFields rff = reportRuntime.getReportFormFields(); + ReportFormFields childReportFormFields = null; + String fieldDisplayName = ""; + String fieldValue = ""; + + for (int c = 0; c < reportCols.size(); c++) { + if(reportCols.get(c)!=null) { + DataColumnType dct = (DataColumnType) reportCols.get(c); + if(nvl(dct.getDependsOnFormField()).length()>0 && nvl(dct.getDependsOnFormField()).indexOf("[")!=-1) { + for(int i = 0 ; i < rff.size(); i++) { + fieldDisplayName = "["+((FormField)rff.getFormField(i)).getFieldDisplayName()+"]"; + fieldValue = ""; + //if(dct.getOriginalDisplayName()==null) dct.setOriginalDisplayName(dct.getDisplayName()); + if (dct.getDependsOnFormField().equals(fieldDisplayName)) { + fieldValue = nvl(request.getParameter(((FormField)rff.getFormField(i)).getFieldName())); + + if (fieldValue.length()>0) { + if(!fieldValue.toUpperCase().equals("Y")) + dct.setDisplayName(fieldValue); + if(!dct.isVisible()) + dct.setVisible(true); + } else { + dct.setVisible(false); + } + } + } + } + } + } + + /* ADDED */ + String displayName = ""; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + + DataColumnType dc = (DataColumnType) iter.next(); + + formatProcessors.add(count,new FormatProcessor( + reportRuntime.getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc + .getColFormat(), reportRuntime.getReportDefType().equals( + AppConstants.RD_SQL_BASED))); + + /* TODO: Add Drilldown URL */ + if (nvl(dc.getDrillDownURL()).length() > 0) { + childReportFormFields = reportRuntime.getChildReportFormFields(request,dc.getDrillDownURL()); + } + if (dc.isVisible()) { + visibleCols.add(count,dc); + //if(dc.getColId().startsWith("group")) { + for (int d = 0; d < reportCols.size(); d++) { + if(reportCols.get(d)!=null) { + DataColumnType dct1 = (DataColumnType) reportCols.get(d); + if(dct1.getColId().equals(dc.getColId()+"_name") && ds.getRowCount()>0) { + displayName = ds.getString(0,dct1.getColId()); + dc.setDisplayName(displayName); + } + } + } + //} + + VisualManager visualManager = reportRuntime.getVisualManager(); + rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(),dc.getDisplayHeaderAlignment(), + visualManager.isColumnVisible(dc.getColId()), visualManager + .getSortByColId().equals(dc.getColId()) ? visualManager + .getSortByAscDesc() : null, true, dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false); + // chr.addColumnHeader(new ColumnHeader(dc.getDisplayName(), + // (dc.getDisplayWidth()>100)?"10%":(""+dc.getDisplayWidth()+"%"))); + } // if + else { + visibleCols.add(count,null); + rd.createColumn(dc.getColId(), AppConstants.HIDDEN, dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(), + false, null,false,dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false); +// formatProcessors.add(count,null); + } + count++; + } // for + + // Utils._assert(chr.size()==ds.getColumnCount(), + // "[ReportRuntime.loadLinearReportData] The number of visible columns + // does not match the number of data columns"); + //TODO: This should be optimized to accept -1 for flat file download + if(maxRows > totalRows) maxRows = totalRows; + ArrayList reportDataList = new ArrayList(); + for (int r = 0; r < maxRows; r++) { + DataRow dr = new DataRow(); + rd.reportDataRows.addDataRow(dr); + + for (int c = 0; c < reportCols.size(); c++) { + if(reportCols.get(c)!=null) { + DataColumnType dct = (DataColumnType) reportCols.get(c); + //Modified since ds is null. + DataValue dv = new DataValue(); + + if(ds.getRowCount()>0){ + if(ds.getColumnIndex(dct.getColId())!= -1) { + dr.addDataValue(dv); + dv.setDisplayValue(ds.getString(r, dct.getColId())); + } else { + continue; + } + + } else { + dv.setDisplayValue(""); + } + dv.setColName(dct.getColName()); + dv.setColId(dct.getColId()); + dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null")); + + //Add Drilldown URL to dv + if (nvl(dct.getDrillDownURL()).length() > 0) { + + if(dv.getDisplayValue().length() > 0) { + dv.setDrillDownURL(reportRuntime.parseDrillDownURL(r, /* c, */ds, dct, request, childReportFormFields)); + dv.setDrillDowninPoPUp(dct.isDrillinPoPUp()!=null?dct.isDrillinPoPUp():false); + } + + if (dv.getDisplayValue().length() == 0) { + //dv.setDisplayValue("[NULL]"); + dv.setDisplayValue(""); + } + } // if + + StringBuffer indentation = new StringBuffer(""); + if(dct.getIndentation()!=null && dct.getIndentation()>0) { + for (int indent=0; indent< dct.getIndentation(); indent++) { + indentation.append("\t"); + } + dv.setNowrap("true"); + } + dv.setIndentation(indentation.toString()); + + if(dct.isVisible()) { + + dv.setVisible(true); + dv.setAlignment(dct.getDisplayAlignment()); + dv.setDisplayTotal(dct.getDisplayTotal()); + dv.setDisplayName(dct.getDisplayName()); + +// if (nvl(dct.getDrillDownURL()).length() > 0) { + +// if(dv.getDisplayValue().length() > 0) { + //TODO: Below Drilldown URL +// dv.setDrillDownURL(reportRuntime.parseDrillDownURL(r, /* c, */ds, dct,request, childReportFormFields)); +// dv.setDrillDowninPoPUp(dct.isDrillinPoPUp()); +// } +// +// if (dv.getDisplayValue().length() == 0) { +// //dv.setDisplayValue("[NULL]"); +// dv.setDisplayValue(""); +// } +// } // if + + } else { + dv.setVisible(false); + dv.setHidden(true); + } + //System.out.println("in Linear report b4" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue()); + + if(dr.getFormatId()!=null) + ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, true); + else + ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, false); + + //System.out.println("in Linear report After" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue()); + } // if reportCols + } // for + reportDataList.add(dr); + } // for + + rd.setReportDataList(reportDataList); + //Only if rownumber options is needed + //rd.addRowNumbers(pageNo, getPageSize()); + DataRow colDataTotalsLinear = null; + if (colDataTotalsLinear == null) + colDataTotalsLinear = reportRuntime.generateColumnDataTotalsLinear(new ArrayList(reportCols), AppUtils.getUserID(request), + reportRuntime.getDbInfo(),request); + + if(colDataTotalsLinear!=null) + rd.setColumnDataTotalsLinear(colDataTotalsLinear, "Total"); + // Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar + rd.applyVisibility(); + } + return rd; + } // loadLinearReportData + + public String formFieldRun(HttpServletRequest request, String nextPage) { + ReportRuntime rr = null; + rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + if(rr!=null) { + ReportJSONRuntime reportJSONRuntime = rr.createFormFieldJSONRuntime(request); + ObjectMapper mapper = new ObjectMapper(); + //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); + //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String jsonInString = ""; + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reportJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + + } + return jsonInString; + } + + return ""; + } + +} // ActionHandler diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionMapping.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionMapping.java new file mode 100644 index 00000000..723b5fd1 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ActionMapping.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +public class ActionMapping extends HashMap { + + public void addAction(Action action) { + put(action.getAction(), action); + } // addAction + + public Action getAction(String actionKey) { + return (Action) get(actionKey); + } // getAction + +} // ActionMapping diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Controller.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Controller.java new file mode 100644 index 00000000..c233b4a0 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/Controller.java @@ -0,0 +1,125 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; +import java.lang.reflect.*; +import javax.servlet.*; +import javax.servlet.http.*; + +import org.openecomp.portalsdk.analytics.controller.*; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException; +import org.openecomp.portalsdk.analytics.model.runtime.ReportParamValues; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class Controller extends org.openecomp.portalsdk.analytics.RaptorObject { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Controller.class); + public Controller() { + } + + public String processRequest(HttpServletRequest request) { + String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), "report.run"); + + return processRequest(actionKey, request); + } // processRequest + + public String processRequest(String actionKey, HttpServletRequest request) { + Action action = null; + try { + action = Globals.getRaptorActionMapping().getAction(actionKey); + if (action == null) + throw new RaptorRuntimeException("Action not found"); + } catch (RaptorException e) { + logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. RaptorException: " + e.getMessage())); +// if (actionKey.equals("system_upgrade")) // System override +// return att.raptor.util.upgrade.SystemUpgrade.upgradeDB(request); + + return (new ErrorHandler()).processFatalError(request, new RaptorRuntimeException( + "[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. Exception: " + e.getMessage())); + } + + try { + Class[] paramTypes = new Class[2]; + paramTypes[0] = Class.forName("javax.servlet.http.HttpServletRequest"); + paramTypes[1] = Class.forName("java.lang.String"); + + Class handlerClass = Class.forName(action.getControllerClass()); + Object handler = handlerClass.newInstance(); + Method handlerMethod = handlerClass.getMethod(action.getControllerMethod(), + paramTypes); + + Object[] paramValues = new Object[2]; + paramValues[0] = request; + paramValues[1] = action.getJspName(); + + return (String) handlerMethod.invoke(handler, paramValues); + } catch (ClassNotFoundException e) { + logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. ClassNotFoundException: " + e.getMessage())); + return (new ErrorHandler()).processFatalError(request, new RaptorRuntimeException( + "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: " + + e.getMessage())); + } catch (IllegalAccessException e) { + logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. IllegalAccessException: " + e.getMessage())); + return (new ErrorHandler()).processFatalError(request, new RaptorRuntimeException( + "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: " + + e.getMessage())); + }catch (InstantiationException e) { + logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. InstantiationException: " + e.getMessage())); + return (new ErrorHandler()).processFatalError(request, new RaptorRuntimeException( + "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: " + + e.getMessage())); + }catch (NoSuchMethodException e) { + logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. NoSuchMethodException: " + e.getMessage())); + return (new ErrorHandler()).processFatalError(request, new RaptorRuntimeException( + "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: " + + e.getMessage())); + }catch (InvocationTargetException e) { + logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action [" + actionKey + + "]. InvocationTargetException: " + e.getMessage())); + return (new ErrorHandler()).processFatalError(request, new RaptorRuntimeException( + "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: " + + e.getMessage())); + } + } // processRequest + + public void handleRequest(HttpServletRequest request, HttpServletResponse response, + ServletContext servletContext) throws Exception { + String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action")); + + handleRequest(actionKey, request, response, servletContext); + } // handleRequest + + public void handleRequest(String actionKey, HttpServletRequest request, + HttpServletResponse response, ServletContext servletContext) throws Exception { + servletContext.getRequestDispatcher("/" + processRequest(actionKey, request)).forward( + request, response); + } // handleRequest + +} // Controller diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ErrorHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ErrorHandler.java new file mode 100644 index 00000000..75d88d0f --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/ErrorHandler.java @@ -0,0 +1,151 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.util.*; +import javax.servlet.http.*; + +import org.openecomp.portalsdk.analytics.error.*; +import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition; +import org.openecomp.portalsdk.analytics.model.runtime.ErrorJSONRuntime; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +public class ErrorHandler extends org.openecomp.portalsdk.analytics.RaptorObject { + + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ErrorHandler.class); + + public ErrorHandler() { + } + + public void processError(HttpServletRequest request, String errorMsg) { + //Log.write(errorMsg, 2); + logger.error(EELFLoggerDelegate.debugLogger, (errorMsg)); + ArrayList error_list = (ArrayList) request.getAttribute(AppConstants.RI_ERROR_LIST); + if (error_list == null) + error_list = new ArrayList(1); + error_list.add(errorMsg); + request.setAttribute(AppConstants.RI_ERROR_LIST, error_list); + } // processError + + public void processError(HttpServletRequest request, RaptorException e) { + processError(request, "Exception: " + e.getMessage()); + } // processError + + private String getSessionLog(HttpServletRequest request) { + String[] sessionVariablesToLog = Globals.getLogVariablesInSession().split(","); + StringBuffer sessionLogStrBuf = new StringBuffer("\n"); + sessionLogStrBuf.append("***** ADDITIONAL INFORMATION ******"); + HttpSession session = request.getSession(); + ReportRuntime rr = (ReportRuntime) session.getAttribute(AppConstants.SI_REPORT_RUNTIME); + ReportDefinition rdef = (ReportDefinition) session.getAttribute(AppConstants.SI_REPORT_DEFINITION); + if(rr!=null) { + sessionLogStrBuf.append("\nWHILE RUNNING"); + sessionLogStrBuf.append("\nReport Id="+rr.getReportID()+";\t"); + sessionLogStrBuf.append("Report Name="+rr.getReportName()+";\t\n"); + } else if (rdef != null) { + sessionLogStrBuf.append("\nWHILE CREATING/UPDATING"); + sessionLogStrBuf.append("\nReport Id="+rdef.getReportID()+";\t"); + sessionLogStrBuf.append("Report Name="+rdef.getReportName()+";\t\n"); + } + for (int i = 0; i < sessionVariablesToLog.length; i++) { + if(session.getAttribute(sessionVariablesToLog[i])!=null) + sessionLogStrBuf.append(sessionVariablesToLog[i]+"="+(String)session.getAttribute(sessionVariablesToLog[i])+";\t"); + } + sessionLogStrBuf.append("\n***********************************"); + sessionLogStrBuf.append("\n"); + return sessionLogStrBuf.toString(); + } + public String processFatalError(HttpServletRequest request, RaptorException e) { + //Log.write("Fatal error [" + e.getClass().getName() + "]: " + nvl(e.getMessage()), 1); + logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Fatal error [" + e.getClass().getName() + "]: " + nvl(e.getMessage())+" "+ getSessionLog(request) + e.getMessage()),AlarmSeverityEnum.MAJOR); + if (e instanceof ReportSQLException) { + String errorSQL = ((ReportSQLException) e).getReportSQL(); + if (nvl(errorSQL).length() > 0) + request.setAttribute("c_error_sql", errorSQL); + } // if + AppUtils.processErrorNotification(request, e); + + request.setAttribute(AppConstants.RI_EXCEPTION, e); + return AppUtils.getErrorPage(); + } // processFatalError + + public String processFatalErrorJSON(HttpServletRequest request, RaptorException e) { + //Log.write("Fatal error [" + e.getClass().getName() + "]: " + nvl(e.getMessage()), 1); + logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Fatal error [" + e.getClass().getName() + "]: " + nvl(e.getMessage())+" "+ getSessionLog(request) + e.getMessage()),AlarmSeverityEnum.MAJOR); + if (e instanceof ReportSQLException) { + String errorSQL = ((ReportSQLException) e).getReportSQL(); + if (nvl(errorSQL).length() > 0) + request.setAttribute("c_error_sql", errorSQL); + } // if + //AppUtils.processErrorNotification(request, e); + + request.setAttribute(AppConstants.RI_EXCEPTION, e); + ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage(e.toString()); + errorJSONRuntime.setStacktrace(getStackTrace(e)); + ObjectMapper mapper = new ObjectMapper(); + //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); + //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String jsonInString = ""; + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + + } + return jsonInString; + } // processFatalError + + public static String getStackTrace(Throwable aThrowable) { + Writer result = new StringWriter(); + PrintWriter printWriter = new PrintWriter(result); + aThrowable.printStackTrace(printWriter); + return result.toString(); + } + public String processFatalErrorWMenu(HttpServletRequest request, RaptorException e) { + //Log.write("Fatal error [" + e.getClass().getName() + "]: " + nvl(e.getMessage()), 1); + logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Fatal error [" + e.getClass().getName() + "]: " + nvl(e.getMessage())+" "+ getSessionLog(request) + e.getMessage()),AlarmSeverityEnum.MAJOR); + if (e instanceof ReportSQLException) { + String errorSQL = ((ReportSQLException) e).getReportSQL(); + if (nvl(errorSQL).length() > 0) + request.setAttribute("c_error_sql", errorSQL); + } // if + AppUtils.processErrorNotification(request, e); + + request.setAttribute(AppConstants.RI_EXCEPTION, e); + return AppUtils.getErrorPageWMenu(); + } // processFatalError + +} // ErrorHandler + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardProcessor.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardProcessor.java new file mode 100644 index 00000000..b193ec4b --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardProcessor.java @@ -0,0 +1,2356 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.ValidationException; +import org.openecomp.portalsdk.analytics.model.ReportHandler; +import org.openecomp.portalsdk.analytics.model.ReportLoader; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.model.base.OrderBySeqComparator; +import org.openecomp.portalsdk.analytics.model.base.OrderSeqComparator; +import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition; +import org.openecomp.portalsdk.analytics.model.definition.ReportSchedule; +import org.openecomp.portalsdk.analytics.model.runtime.FormField; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.DbUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.XSSFilter; +import org.openecomp.portalsdk.analytics.xmlobj.ChartDrillFormfield; +import org.openecomp.portalsdk.analytics.xmlobj.ColFilterType; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.DataSourceType; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.analytics.xmlobj.FormatType; +import org.openecomp.portalsdk.analytics.xmlobj.JavascriptItemType; +import org.openecomp.portalsdk.analytics.xmlobj.Marker; +import org.openecomp.portalsdk.analytics.xmlobj.ObjectFactory; +import org.openecomp.portalsdk.analytics.xmlobj.SemaphoreType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +/**
+ * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting)
+ *
+ * + * --------------------------------------------------------------------------------------------------
+ * WizardProcessor.java - This class is used to process the user input provided in the wizard.
+ * It is called in creation as well as updation process. It builds report xml via JAXB using user
+ * input. This is vital one, to store meta information of each report
+ * ---------------------------------------------------------------------------------------------------
+ * + * + * Change Log

+ * + * 31-Aug-2009 : Version 8.5.1 (Sundar);
  • For Time Series multi series property is exposed.
+ * 28-Aug-2009 : Version 8.5.1 (Sundar);
  • If user login id is null, it would display user name when user is added for schedule.
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 12-Aug-2009 : Version 8.5 (Sundar);
  • For Line Charts too options are captured and rendering is customized.
+ * 29-Jul-2009 : Version 8.4 (Sundar);
  • Maximum Excel Download size would be persisted if changed.
+ * 14-Jul-2009 : Version 8.4 (Sundar);
  • Schedule feature is added to Dashboard Reports.
+ * 29-Jun-2009 : Version 8.4 (Sundar);
  • Options for Compare to Previous year Chart are processed.
  • + *
  • In the Bar chart Last Occuring Series/Category can be plotted as Bar or Line Renderer.
  • + *
+ * 22-Jun-2009 : Version 8.4 (Sundar);
  • processChart method is modified to accommodate creating + * Bar Charts, Time Difference Charts and adding generic chart options.
+ * + */ + +public class WizardProcessor extends org.openecomp.portalsdk.analytics.RaptorObject { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WizardProcessor.class); + + public WizardProcessor() { + } + + private String adjustDataType(String oracleDataType) { + return oracleDataType.equals("VARCHAR2") ? AppConstants.CT_CHAR : oracleDataType; + // Probably should be expanded to convert any CHAR or VARCHAR type to + // CT_CHAR, number type to CT_NUMBER and date to CT_DATE + } // adjustDataType + + public void persistReportDefinition(HttpServletRequest request, ReportDefinition rdef) + throws RaptorException { + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + if (rr != null && rr.getReportID().equals(rdef.getReportID())) + request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME); + rdef.persistReport(request); + } // persistReportDefinition + + public void processWizardStep(HttpServletRequest request) throws Exception { + String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION), + AppConstants.WA_BACK); + + String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, reportID); + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + + String curStep = rdef.getWizardSequence().getCurrentStep(); + String curSubStep = rdef.getWizardSequence().getCurrentSubStep(); + if (AppUtils.getRequestNvlValue(request, "showDashboardOptions").length()<=0) + request.setAttribute("showDashboardOptions", "F"); + logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^curStep " + curStep + " " + curSubStep + " " + action)); + boolean reportUpdated = false; + if (!action.equals(AppConstants.WA_BACK)) { + if (curStep.equals(AppConstants.WS_DEFINITION)) { + reportUpdated = processDefinition(request); + } else if (curStep.equals(AppConstants.WS_SQL)) { + if (action.equals(AppConstants.WA_VALIDATE)) + reportUpdated = processValidateSQL(request); + } else if (curStep.equals(AppConstants.WS_TABLES)) { + if (curSubStep.equals(AppConstants.WSS_ADD)) + reportUpdated = processTableAdd(request); + else if (curSubStep.equals(AppConstants.WSS_EDIT)) + reportUpdated = processTableEdit(request); + else if (action.equals(AppConstants.WA_DELETE)) + reportUpdated = processTableDelete(request); + } else if (curStep.equals(AppConstants.WS_COLUMNS)) { + if (curSubStep.equals(AppConstants.WSS_ADD) + || curSubStep.equals(AppConstants.WSS_EDIT) || action.equals(AppConstants.WA_SAVE) || action.equals(AppConstants.WA_NEXT)) { + reportUpdated = processColumnAddEdit(request, curSubStep + .equals(AppConstants.WSS_EDIT) || curSubStep + .equals(AppConstants.WA_MODIFY)); + //reportUpdated = processColumnAddEdit(request, true); + } + else if (curSubStep.equals(AppConstants.WSS_ADD_MULTI)) + reportUpdated = processColumnAddMulti(request); + else if (curSubStep.equals(AppConstants.WSS_ORDER_ALL)) + reportUpdated = processColumnOrderAll(request); + else if (action.equals(AppConstants.WA_DELETE)) + reportUpdated = processColumnDelete(request); + else if (action.equals(AppConstants.WA_MOVE_UP)) + reportUpdated = processColumnMoveUp(request); + else if (action.equals(AppConstants.WA_MOVE_DOWN)) + reportUpdated = processColumnMoveDown(request); + } else if (curStep.equals(AppConstants.WS_FORM_FIELDS)) { + if (curSubStep.equals(AppConstants.WSS_ADD) + || curSubStep.equals(AppConstants.WSS_EDIT)) + reportUpdated = processFormFieldAddEdit(request, curSubStep + .equals(AppConstants.WSS_EDIT), action); + else if (action.equals(AppConstants.WA_DELETE)) + reportUpdated = processFormFieldDelete(request); + else if (action.equals(AppConstants.WA_MOVE_UP)) + reportUpdated = processFormFieldMoveUp(request); + else if (action.equals(AppConstants.WA_MOVE_DOWN)) + reportUpdated = processFormFieldMoveDown(request); + else if (action.equals(AppConstants.WSS_ADD_BLANK)) + reportUpdated = processFormFieldBlank(request); + else if (action.equals(AppConstants.WSS_INFO_BAR)) + reportUpdated = processFormFieldInfoBar(request); + } else if (curStep.equals(AppConstants.WS_FILTERS)) { + if (curSubStep.equals(AppConstants.WSS_ADD) + || curSubStep.equals(AppConstants.WSS_EDIT)) + reportUpdated = processFilterAddEdit(request, curSubStep + .equals(AppConstants.WSS_EDIT)); + else if (action.equals(AppConstants.WA_DELETE)) + reportUpdated = processFilterDelete(request); + } else if (curStep.equals(AppConstants.WS_SORTING)) { + if (curSubStep.equals(AppConstants.WSS_ADD) + || curSubStep.equals(AppConstants.WSS_EDIT)) + reportUpdated = processSortAddEdit(request, curSubStep + .equals(AppConstants.WSS_EDIT)); + else if (curSubStep.equals(AppConstants.WSS_ORDER_ALL)) + reportUpdated = processSortOrderAll(request); + else if (action.equals(AppConstants.WA_DELETE)) + reportUpdated = processSortDelete(request); + else if (action.equals(AppConstants.WA_MOVE_UP)) + reportUpdated = processSortMoveUp(request); + else if (action.equals(AppConstants.WA_MOVE_DOWN)) + reportUpdated = processSortMoveDown(request); + } else if (curStep.equals(AppConstants.WS_JAVASCRIPT)) { + if (action.equals(AppConstants.WSS_ADD)) + reportUpdated = processAddJavascriptElement(request); + else if (action.equals(AppConstants.WA_SAVE)) + reportUpdated = processSaveJavascriptElement(request); + else if (action.equals(AppConstants.WA_DELETE)) + reportUpdated = processDeleteJavascriptElement(request); + else + reportUpdated = processJavascript(request); + } else if (curStep.equals(AppConstants.WS_CHART)) { + reportUpdated = processChart(request, action); + } else if (curStep.equals(AppConstants.WS_USER_ACCESS)) { + reportUpdated = processUserAccess(request, action); + } else if (curStep.equals(AppConstants.WS_REPORT_LOG)) { + if (action.equals(AppConstants.WA_DELETE_USER)) + reportUpdated = processClearLog(request); + } else if (curStep.equals(AppConstants.WS_SCHEDULE)) { + reportUpdated = processSchedule(request, action); + } else if(curStep.equals(AppConstants.WS_DATA_FORECASTING)) { + reportUpdated = processForecasting(request, action); + } + /****For Report Maps - Start*****/ + else if (curStep.equals(AppConstants.WS_MAP)) { + reportUpdated = processMap(request, action); + } + /****For Report Maps - End*****/ + + // else + } + if (reportUpdated) + persistReportDefinition(request, rdef); + } // processWizardStep + + public void processImportSemaphorePopup(HttpServletRequest request) throws RaptorException { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String importReportId = AppUtils + .getRequestNvlValue(request, AppConstants.RI_REPORT_ID); + ReportRuntime rr = (new ReportHandler()).loadReportRuntime(request, importReportId, + false); + + ArrayList importedList = new ArrayList(); + if (rr.getSemaphoreList() != null) + for (Iterator iter = rr.getSemaphoreList().getSemaphore().iterator(); iter + .hasNext();) { + SemaphoreType sem = rdef.addSemaphore(new ObjectFactory(), + (SemaphoreType) iter.next()); + importedList + .add(new IdNameValue(sem.getSemaphoreId(), sem.getSemaphoreName())); + } // for + + if (importedList.size() > 0) { + request.setAttribute(AppConstants.RI_DATA_SET, importedList); + persistReportDefinition(request, rdef); + } // if + } // processImportSemaphorePopup + + public void processSemaphorePopup(HttpServletRequest request) throws RaptorException { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String semaphoreId = AppUtils.getRequestNvlValue(request, "semaphoreId"); + String semaphoreName = AppUtils.getRequestNvlValue(request, "semaphoreName"); + String semaphoreType = AppUtils.getRequestNvlValue(request, "semaphoreType"); + + SemaphoreType semaphore = rdef.getSemaphoreById(semaphoreId); + if (semaphore == null) { + semaphore = rdef.addSemaphoreType(new ObjectFactory(), semaphoreName, + semaphoreType, null); + semaphoreId = semaphore.getSemaphoreId(); + request.setAttribute("semaphoreId", semaphoreId); + } else { + rdef.deleteSemaphore(semaphore); + semaphore.setSemaphoreName(semaphoreName); + semaphore.setSemaphoreType(semaphoreType); + + rdef.setSemaphore(semaphore); + } + + String[] formatId = request.getParameterValues("formatId"); + String[] lessThanValue = request.getParameterValues("lessThanValue"); + String[] expression = request.getParameterValues("expression"); + String[] bold = request.getParameterValues("bold"); + String[] italic = request.getParameterValues("italic"); + String[] underline = request.getParameterValues("underline"); + String[] bgColor = request.getParameterValues("bgColor"); + String[] fontColor = request.getParameterValues("fontColor"); + String[] fontFace = request.getParameterValues("fontFace"); + String[] fontSize = request.getParameterValues("fontSize"); + //String[] anyFmt = request.getParameterValues("anyFmt"); + + // String[] alignment = request.getParameterValues("alignment"); + + for (int i = 0; i < lessThanValue.length; i++) + if (i == 0 || nvl(lessThanValue[i]).length() > 0) { + FormatType fmt = null; + if (i == 0 || nvl(formatId[i]).length() > 0) + fmt = rdef.getSemaphoreFormatById(semaphore, nvl(formatId[i])); + if (fmt == null) + fmt = rdef.addEmptyFormatType(new ObjectFactory(), semaphore); + + fmt.setLessThanValue(nvl(lessThanValue[i])); + fmt.setExpression(nvl(expression[i])); + fmt.setBold(bold[i].equals("Y")); + fmt.setItalic(italic[i].equals("Y")); + fmt.setUnderline(underline[i].equals("Y")); + fmt.setBgColor(bgColor[i]); + fmt.setFontColor(fontColor[i]); + fmt.setFontFace(fontFace[i]); + fmt.setFontSize(fontSize[i]); + //fmt.setAnyFmt((anyFmt[i]!=null)?anyFmt[i].startsWith("Y"):false); + // fmt.setAlignment(alignment[i]); + } else if (nvl(formatId[i]).length() > 0) + rdef.deleteFormatType(semaphore, formatId[i]); + + persistReportDefinition(request, rdef); + } // processSemaphorePopup + + private boolean processDefinition(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String reportName = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportName")); + String reportDescr = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportDescr")); + String folderId = AppUtils.getRequestNvlValue(request, "folder_id"); + boolean isAllowSchedule = (AppUtils.getRequestNvlValue(request, "allowSchedule").length()<=0?"N":AppUtils.getRequestNvlValue(request, "allowSchedule")).startsWith("Y"); + boolean isColumnGroup = (AppUtils.getRequestNvlValue(request, "multiGroupColumn").length()<=0?"N":AppUtils.getRequestNvlValue(request, "multiGroupColumn")).startsWith("Y"); + boolean isTopDown = (AppUtils.getRequestNvlValue(request, "topDown").length()<=0?"N":AppUtils.getRequestNvlValue(request, "topDown")).startsWith("Y"); + boolean isSizedByContent= (AppUtils.getRequestNvlValue(request, "sizedByContent").length()<=0?"N":AppUtils.getRequestNvlValue(request, "sizedByContent")).startsWith("Y"); + boolean reportsInNewWindow = false; + boolean hideFormFieldAfterRun = false; + + /*recurrance in schedule tab - Start*/ + String isOneTimeScheduleAllowed = nvl(AppUtils.getRequestValue(request, "isOneTimeScheduleAllowed"),"N"); + String isHourlyScheduleAllowed = nvl(AppUtils.getRequestValue(request, "isHourlyScheduleAllowed"),"N"); + String isDailyScheduleAllowed = nvl(AppUtils.getRequestValue(request, "isDailyScheduleAllowed"),"N"); + String isDailyMFScheduleAllowed = nvl(AppUtils.getRequestValue(request, "isDailyMFScheduleAllowed"),"N"); + String isWeeklyScheduleAllowed = nvl(AppUtils.getRequestValue(request, "isWeeklyScheduleAllowed"),"N"); + String isMonthlyScheduleAllowed = nvl(AppUtils.getRequestValue(request, "isMonthlyScheduleAllowed"),"N"); + //System.out.println("//////////// + isOneTimeScheduleAllowed : " + isOneTimeScheduleAllowed); + /*recurrance in schedule tab - End*/ + + + if (reportDescr.length() > 1000) + reportDescr = reportDescr.substring(0, 1000); + boolean reportUpdated; + + String reportType = AppUtils.getRequestNvlValue(request, "reportType"); + + + + //rdef.setReportName(reportName); + //rdef.setReportDescr(reportDescr); + //rdef.setReportType(reportType); + rdef.setFolderId(folderId); +// debugLogger.debug("setting folder ID = " + folderId); + if(reportType.equals(AppConstants.RT_DASHBOARD)) { + rdef.setReportName(reportName); + rdef.setReportDescr(reportDescr); + rdef.setReportType(reportType); + String dashboardLayoutHTML = AppUtils.getRequestNvlValue(request, "dashboardLayoutHTML"); + rdef.setDashboardLayoutHTML(dashboardLayoutHTML); + String dataContainerHeight = nvl(AppUtils.getRequestValue(request, "heightContainer"), "auto"); + String dataContainerWidth = nvl(AppUtils.getRequestValue(request, "widthContainer"), "auto"); + rdef.setDataContainerHeight(dataContainerHeight); + rdef.setDataContainerWidth(dataContainerWidth); + rdef.setAllowSchedule(isAllowSchedule?"Y":"N"); + + + /* + String numDashCols = AppUtils.getRequestNvlValue(request, "numDashCols"); + String reports1 = AppUtils.getRequestNvlValue(request, "reports1"); + String reports2 = AppUtils.getRequestNvlValue(request, "reports2"); + String reports3 = AppUtils.getRequestNvlValue(request, "reports3"); + String reports4 = AppUtils.getRequestNvlValue(request, "reports4"); + String repBgColor1 = AppUtils.getRequestNvlValue(request, "repBgColor1"); + String repBgColor2 = AppUtils.getRequestNvlValue(request, "repBgColor2"); + String repBgColor3 = AppUtils.getRequestNvlValue(request, "repBgColor3"); + String repBgColor4 = AppUtils.getRequestNvlValue(request, "repBgColor4"); + + //List reports = rdef.getDashBoardReports(); + rdef.setNumDashCols(numDashCols); + DashboardReports reportsList = new DashboardReportsImpl(); + + String reports[] = new String[]{reports1, reports2, reports3, reports4}; + String repBgColors[] = new String[]{repBgColor1, repBgColor2, repBgColor3, repBgColor4}; + for (int i = 0; i < reports.length; i++) { + Reports report = new ReportsImpl(); + report.setReportId(reports[i]); + report.setBgcolor(repBgColors[i]); + reportsList.getReportsList().add(report); + } + + + + rdef.setDashBoardReports(reportsList); + */ + reportUpdated = true; + +// reportUpdated = (!(reportName.equals(nvl(rdef.getReportName())) +// && reportDescr.equals(nvl(rdef.getReportDescr())) +// && reportType.equals(nvl(rdef.getReportType())) +// && numDashCols.equals(nvl(rdef.getNumDashCols())))); +//// && rdef.getR + + if (rdef.getWizardSequence() instanceof WizardSequence) + rdef.generateWizardSequence(request); + + } else { + + if (AppUtils.getRequestNvlValue(request, "reportType").equals(AppConstants.RT_CROSSTAB) || rdef.getReportType().equals(AppConstants.RT_CROSSTAB)) { + + String widthNo = AppUtils.getRequestNvlValue(request, "widthNo"); + if(nvl(widthNo).endsWith("px")) + rdef.setWidthNoColumn(widthNo); + else + rdef.setWidthNoColumn(widthNo+"px"); + } + + String dataGridAlign = AppUtils.getRequestNvlValue(request, "dataGridAlign"); + if(nvl(dataGridAlign).length()>0) { + rdef.setDataGridAlign(dataGridAlign); + } else { + rdef.setDataGridAlign("left"); + } + + String pdfImgLogo = AppUtils.getRequestNvlValue(request, "pdfImg"); + if(nvl(pdfImgLogo).length()>0) + rdef.setPdfImg(pdfImgLogo); + else + rdef.setPdfImg(null); + String emptyMessage = AppUtils.getRequestNvlValue(request, "emptyMessage"); + if(nvl(emptyMessage).length()>0) + rdef.setEmptyMessage(emptyMessage); + else + rdef.setEmptyMessage(""); + String formHelp = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "formHelp")); + //String rDashboardType = nvl(AppUtils.getRequestValue(request, "showDashboardOptions"), "N"); + //rdef.setDashboardType(rDashboardType.equals("Y")); + int excelDownloadSize = 500; + try { + excelDownloadSize = Integer.parseInt(AppUtils.getRequestValue(request, "excelDownloadSize")); + } catch (NumberFormatException ex) {} + if(AppUtils.getRequestNvlValue(request, "excelDownloadSize").length()>0) + rdef.setMaxRowsInExcelDownload(Integer.parseInt(AppUtils.getRequestValue(request, "excelDownloadSize"))); + if(AppUtils.getRequestNvlValue(request, "reportInNewWindow").length()>0) + reportsInNewWindow = AppUtils.getRequestNvlValue(request,"reportInNewWindow").equals("Y"); + if(AppUtils.getRequestNvlValue(request, "hideFormFieldsAfterRun").length()>0) + hideFormFieldAfterRun = AppUtils.getRequestNvlValue(request,"hideFormFieldsAfterRun").equals("Y"); + + + if(AppUtils.getRequestNvlValue(request, "displayFolderTree").length()>0) + rdef.setDisplayFolderTree(AppUtils.getRequestNvlValue(request,"displayFolderTree").equals("Y")); + else + rdef.setDisplayFolderTree(false); + String dataSource = AppUtils.getRequestNvlValue(request, "dataSource"); + String dbType = Globals.getDBType(); + String schemaSql = Globals.getRemoteDbSchemaSqlWithWhereClause(); + schemaSql = schemaSql.replace("[schema_id]", dataSource); + DataSet ds = null; + try { + ds = DbUtils.executeQuery(schemaSql); + + String prefix = "", desc = ""; + + for (int i = 0; i < ds.getRowCount(); i++) { + dbType = ds.getItem(i, 2); + } + } + catch (Exception e) {} + + int pageSize = Globals.getDefaultPageSize(); + try { + pageSize = Integer.parseInt(AppUtils.getRequestValue(request, "pageSize")); + } catch (NumberFormatException e) { + } + String rApproved = nvl(AppUtils.getRequestValue(request, "menuApproved"), "N"); + String menuID = ""; + String[] menuIDs = request.getParameterValues("menuID"); + if (menuIDs != null) + for (int i = 0; i < menuIDs.length; i++) + menuID += (menuID.length() == 0 ? "" : "|") + menuIDs[i]; + /* else + menuID = "";*/ + +// boolean additionalFieldsShown = AppUtils.getRequestNvlValue(request, +// "additionalFieldsShown").equals("Y"); + boolean rRCSDisabled = AppUtils.getRequestNvlValue(request, "runtimeColSortDisabled").equals("Y"); + String reportDefType = AppUtils.getRequestNvlValue(request, "reportDefType"); + String dataContainerHeight = nvl(AppUtils.getRequestValue(request, "heightContainer"), "auto"); + String dataContainerWidth = nvl(AppUtils.getRequestValue(request, "widthContainer"), "auto"); + + String displayOptions = nvl(AppUtils.getRequestValue(request, "hideForm"), "N") + + nvl(AppUtils.getRequestValue(request, "hideChart"), "N") + + nvl(AppUtils.getRequestValue(request, "hideData"), "N") + + nvl(AppUtils.getRequestValue(request, "hideBtns"), "N") + + nvl(AppUtils.getRequestValue(request, "hideMap"), "N") + + nvl(AppUtils.getRequestValue(request, "hideExcelIcons"), "N") + + nvl(AppUtils.getRequestValue(request, "hidePDFIcons"), "N"); +/* StringBuffer dashboardOptions = new StringBuffer(""); + dashboardOptions.append((nvl(AppUtils.getRequestValue(request, "hide"),"chart").equals("chart"))?"Y":"N"); + dashboardOptions.append((nvl(AppUtils.getRequestValue(request, "hide"),"").equals("data"))?"Y":"N"); + dashboardOptions.append((nvl(AppUtils.getRequestValue(request, "hideBtns"),"").equals("Y"))?"Y":"N");*/ + + String numFormCols = nvl(AppUtils.getRequestValue(request, "numFormCols"), "1"); + String reportTitle = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportTitle")); + String reportSubTitle = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportSubTitle")); + String reportHeader = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportHeader")); + String reportFooter = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportFooter")); + + int frozenColumns = 0; + try { + frozenColumns = Integer.parseInt(AppUtils.getRequestValue(request, "frozenColumns")); + } catch (NumberFormatException ex) { + + } + +/* reportUpdated = (!(reportName.equals(nvl(rdef.getReportName())))) + && (!(reportDescr.equals(nvl(rdef.getReportDescr())))) + && (!(formHelp.equals(nvl(rdef.getFormHelpText())))) + && (!(reportType.equals(nvl(rdef.getReportType())))) + && (pageSize != rdef.getPageSize()) && + // rPublic.equals(rdef.isPublic()?"Y":"N")&& + (!(menuID.equals(nvl(rdef.getMenuID())))) + && (!(rApproved.equals(rdef.isMenuApproved()))) && (additionalFieldsShown ? ((!(rRCSDisabled + .equals(rdef.isRuntimeColSortDisabled()))) + && (!(displayOptions.equals(nvl(rdef.getDisplayOptions())))) + && (!(dashboardOptions.equals(nvl(rdef.getDashboardOptions())))) + && (!(numFormCols.equals(nvl(rdef.getNumFormCols())))) + && (!(reportTitle.equals(nvl(rdef.getReportTitle())))) + && (!(reportSubTitle.equals(nvl(rdef.getReportSubTitle())))) + && (!(reportHeader.equals(nvl(rdef.getReportHeader())))) && (!(reportFooter + .equals(nvl(rdef.getReportFooter()))))&& (reportsInNewWindow != rdef.isReportInNewWindow())):true); +*/ +/* reportUpdated = rRCSDisabled ==(rdef.isRuntimeColSortDisabled() + && displayOptions.equals(nvl(rdef.getDisplayOptions())) + //&& dashboardOptions.equals(nvl(rdef.getDashboardOptions())) + && numFormCols.equals(nvl(rdef.getNumFormCols())) + && reportTitle.equals(nvl(rdef.getReportTitle())) + && reportSubTitle.equals(nvl(rdef.getReportSubTitle())) + && reportHeader.equals(nvl(rdef.getReportHeader())) + && reportsInNewWindow == rdef.isReportInNewWindow() + && reportFooter.equals(nvl(rdef.getReportFooter()))) + ;*/ + + + /*reportUpdated = (!(reportName.equals(nvl(rdef.getReportName())) + && reportDescr.equals(nvl(rdef.getReportDescr())) + && formHelp.equals(nvl(rdef.getFormHelpText())) + && reportType.equals(nvl(rdef.getReportType())) + && (pageSize == rdef.getPageSize()) + && excelDownloadSize == rdef.getMaxRowsInExcelDownload() + && reportsInNewWindow == rdef.isReportInNewWindow() + && displayOptions.equals(rdef.getDisplayOptions()) + && dataContainerHeight.equals(rdef.getDataContainerHeight()) + && dataContainerWidth.equals(rdef.getDataContainerWidth()) + && (isAllowSchedule ==(rdef.isAllowSchedule())) + // rPublic.equals(rdef.isPublic()?"Y":"N")&& + && menuID.equals(nvl(rdef.getMenuID())) + && rApproved.equals(rdef.isMenuApproved() ? "Y" : "N") && (rRCSDisabled + == ((rdef.isRuntimeColSortDisabled()) + && displayOptions.equals(nvl(rdef.getDisplayOptions())) + //&& dashboardOptions.equals(nvl(rdef.getDashboardOptions())) + && numFormCols.equals(nvl(rdef.getNumFormCols())) + && reportTitle.equals(nvl(rdef.getReportTitle())) + && reportSubTitle.equals(nvl(rdef.getReportSubTitle())) + && isOneTimeScheduleAllowed.equals(nvl(rdef.getIsOneTimeScheduleAllowed())) + && isHourlyScheduleAllowed.equals(nvl(rdef.getIsHourlyScheduleAllowed())) + && isDailyScheduleAllowed.equals(nvl(rdef.getIsDailyScheduleAllowed())) + && isDailyMFScheduleAllowed.equals(nvl(rdef.getIsDailyMFScheduleAllowed())) + && isWeeklyScheduleAllowed.equals(nvl(rdef.getIsWeeklyScheduleAllowed())) + && isMonthlyScheduleAllowed.equals(nvl(rdef.getIsMonthlyScheduleAllowed())) + && reportHeader.equals(nvl(rdef.getReportHeader())) && reportFooter + .equals(nvl(rdef.getReportFooter())))) + )); */ + rdef.setReportName(reportName); + rdef.setReportDescr(reportDescr); + rdef.setFormHelpText(formHelp); + rdef.setReportType(reportType); + rdef.setPageSize(pageSize); + rdef.setDBInfo(dataSource); + rdef.setDBType(dbType); + rdef.setDisplayOptions(displayOptions); + rdef.setDataContainerHeight(dataContainerHeight); + rdef.setDataContainerWidth(dataContainerWidth); + rdef.setAllowSchedule(isAllowSchedule?"Y":"N"); + rdef.setMultiGroupColumn(isColumnGroup?"Y":"N"); + rdef.setTopDown(isTopDown?"Y":"N"); + rdef.setSizedByContent(isSizedByContent?"Y":"N"); + // rdef.setPublic(rPublic.equals("Y")); + rdef.setMenuID(menuID); + rdef.setMenuApproved(rApproved.equals("Y")); + if (reportDefType.length() > 0) + rdef.setReportDefType(reportDefType); +/* if(rdef.isDashboardType()) { + rdef.setDashboardOptions(dashboardOptions.toString()); + }*/ + rdef.setHideFormFieldAfterRun(hideFormFieldAfterRun); + rdef.setReportInNewWindow(reportsInNewWindow); + rdef.setRuntimeColSortDisabled(rRCSDisabled); + rdef.setNumFormCols(numFormCols); + rdef.setReportTitle(reportTitle); + rdef.setReportSubTitle(reportSubTitle); + rdef.setReportHeader(reportHeader); + rdef.setReportFooter(reportFooter); + rdef.setIsOneTimeScheduleAllowed(isOneTimeScheduleAllowed); + rdef.setIsHourlyScheduleAllowed(isHourlyScheduleAllowed); + rdef.setIsDailyScheduleAllowed(isDailyScheduleAllowed); + rdef.setIsDailyMFScheduleAllowed(isDailyMFScheduleAllowed); + rdef.setIsWeeklyScheduleAllowed(isWeeklyScheduleAllowed); + rdef.setIsMonthlyScheduleAllowed(isMonthlyScheduleAllowed); + rdef.setFrozenColumns(frozenColumns); + + } // if + + if (rdef.getWizardSequence() instanceof WizardSequence) + rdef.generateWizardSequence(request); + + + /* + * if(formHelp.length()>255) formHelp = formHelp.substring(0, 255); + */ + + + // String rPublic = nvl(AppUtils.getRequestValue(request, "public"), + // "N"); + // String menuID = AppUtils.getRequestNvlValue(request, "menuID"); + +// boolean dashboardOptionsShown = AppUtils.getRequestNvlValue(request, +// "dashboardOptionsShown").equals("Y"); + + reportUpdated = true; + + if (rdef.getReportID().equals("-1")) + // Always need to persist new report - in case it is a copy + reportUpdated = true; + + return reportUpdated; + } // processDefinition + + private boolean processTableAdd(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String tableName = AppUtils.getRequestNvlValue(request, "tableName").toUpperCase(); + String tableId = rdef.getUniqueTableId(tableName); + + String joinTableExpr = null; + String joinTableId = null; + + DataSourceType joinTable = + rdef.getTableById(AppUtils.getRequestValue(request, "joinTableName")); + if (joinTable != null) { + String joinTableName = joinTable.getTableName(); + joinTableId = joinTable.getTableId(); + + String joinExpr = AppUtils.getRequestNvlValue(request, "joinExpr").toUpperCase(); + + joinTableExpr = joinExpr.replaceAll("\\["+tableName+"\\]", tableId); + joinTableExpr = joinTableExpr.replaceAll("\\["+joinTableName+"\\]", joinTableId); +// debugLogger.debug("joinExpr : "+joinExpr+"\njoinTableExpr : "+ joinTableExpr); + } + + rdef.addDataSourceType(new ObjectFactory(), tableId, tableName, AppUtils + .getRequestNvlValue(request, "tablePK"), AppUtils.getRequestNvlValue(request, + "displayName"), joinTableId, joinTableExpr, null); + + rdef.setOuterJoin(rdef.getTableById(tableId), AppUtils.getRequestNvlValue(request, + "outerJoin")); + rdef.resetCache(true); + + return true; + } // processTableAdd + + private boolean processTableEdit(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + DataSourceType dst = rdef.getTableById(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + + String displayName = XSSFilter.filterRequest(AppUtils.getRequestNvlValue(request, "displayName")); + String outerJoin = AppUtils.getRequestNvlValue(request, "outerJoin"); + + String tableName = AppUtils.getRequestNvlValue(request, "tableName").toUpperCase(); + String joinTableId = AppUtils.getRequestNvlValue(request, "joinTableName"); + + String joinExpr = AppUtils.getRequestNvlValue(request, "joinExpr").toUpperCase(); + + String joinTableExpr = null; + if(joinExpr.length()!=0){ + joinTableExpr = joinExpr.replaceAll("\\["+tableName+"\\]", rdef.getTableByDBName(tableName).getTableId()); + joinTableExpr = joinTableExpr.replaceAll("\\["+rdef.getTableById(joinTableId).getTableName().toUpperCase()+"\\]", joinTableId); + dst.setRefDefinition(joinTableExpr); + } + boolean reportUpdated = (!displayName.equals(nvl(dst.getDisplayName())) || + !outerJoin.equals(rdef.getOuterJoinType(dst)) || + !(joinExpr.length()==0)); + + dst.setDisplayName(displayName); + rdef.setOuterJoin(dst, outerJoin); + if (reportUpdated) + rdef.resetCache(true); + + return true; // reportUpdated; + } // processTableEdit + + + private boolean processTableDelete(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.deleteDataSourceType(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + return true; + } // processTableDelete + + private boolean processColumnAddEdit(HttpServletRequest request, boolean isEdit) + throws Exception { + if(!isEdit) { + return true; + } + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + DataColumnType currColumn = null; + + String tableId = null; + String colName = null; + String dataType = null; + if (isEdit) { + currColumn = rdef.getColumnById(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + + if(currColumn!=null) { + tableId = currColumn.getTableId(); + colName = currColumn.getDbColName(); // currColumn.getColName(); + dataType = currColumn.getDbColType(); + } + } else { + String colData = AppUtils.getRequestNvlValue(request, "columnDetails"); + if(nvl(colData).length()>0) { + tableId = colData.substring(0, colData.indexOf('|')); + colName = colData.substring(tableId.length() + 1, + colData.indexOf('|', tableId.length() + 1)).toUpperCase(); + dataType = colData.substring(tableId.length() + colName.length() + 2); + } + } // else + + String exprFormula = AppUtils.getRequestNvlValue(request, "exprFormula"); + + String colNameValue = null; + if (exprFormula.length() > 0) + if (exprFormula.equals("_exprText_")) + colNameValue = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestValue(request, "exprText")); + else if (exprFormula.equals("COUNT(*)")) + colNameValue = exprFormula; + else + colNameValue = exprFormula + " " + colName + ")"; + else + colNameValue = colName; + + int displayWidth = -1; + try { + displayWidth = Integer.parseInt(AppUtils.getRequestValue(request, "displayWidth")); + } catch (NumberFormatException e) { + } + + String sColId = isEdit ? currColumn.getColId() : (nvl(colName).length()>0?rdef.getUniqueColumnId(colName):null); + String drillDownParams = AppUtils.getRequestValue(request, "drillDownParams"); + if (drillDownParams != null) { + // Replacing references to [this] with [col_id] + while (drillDownParams.indexOf("[this]") >= 0) { + int startIdx = drillDownParams.indexOf("[this]"); + StringBuffer sb = new StringBuffer(); + + if (startIdx > 0) + sb.append(drillDownParams.substring(0, startIdx)); + sb.append("[" + sColId + "]"); + if (startIdx + 6 < drillDownParams.length() - 1) + sb.append(drillDownParams.substring(startIdx + 5)); + drillDownParams = sb.toString(); + } // while + } // if + + String crossTabValue = null; + boolean isVisible = AppUtils.getRequestFlag(request, "visible"); + boolean isSortable = AppUtils.getRequestFlag(request, "sortable"); + String nowrap = AppUtils.getRequestNvlValue(request, "nowrap"); + int indentation = 0; + try { + indentation = Integer.parseInt(AppUtils.getRequestNvlValue(request, "indentation")); + }catch (NumberFormatException e) { + } + String dependsOnFormField = AppUtils.getRequestNvlValue(request, "dependsOnFormField"); + boolean isGroupBreak = AppUtils.getRequestFlag(request, "groupBreak"); + String groupByPosStr = AppUtils.nvls(AppUtils.getRequestValue(request, "groupByPos"), "0"); + int groupByPos = Integer.parseInt(groupByPosStr); + currColumn.setGroupByPos(groupByPos); + + if(groupByPos > 0) { + String subTotalCustomText = AppUtils.nvls(AppUtils.getRequestValue(request, "subTotalCustomText"), "Sub Total"); + currColumn.setSubTotalCustomText(subTotalCustomText); + + boolean hideRepeatedKey = AppUtils.getRequestFlag(request, "hideRepeatedKeys"); + currColumn.setHideRepeatedKey(hideRepeatedKey); + } + + String displayTotal = AppUtils.getRequestNvlValue(request, "displayTotal"); + String widthInPxls = AppUtils.getRequestNvlValue(request, "widthInPxls"); + + if (rdef.getReportType().equals(AppConstants.RT_CROSSTAB)) { + + + + crossTabValue = AppUtils.getRequestValue(request, "crossTabValue"); + isVisible = nvl(crossTabValue).equals(AppConstants.CV_ROW) + || nvl(crossTabValue).equals(AppConstants.CV_COLUMN) + || nvl(crossTabValue).equals(AppConstants.CV_VALUE); + isGroupBreak = nvl(crossTabValue).equals(AppConstants.CV_ROW) + || nvl(crossTabValue).equals(AppConstants.CV_COLUMN); + + if (nvl(crossTabValue).equals(AppConstants.CV_VALUE)) + displayTotal += "|" + + AppUtils.getRequestNvlValue(request, "displayTotalPerRow"); + else + displayTotal = ""; + } // if + + String displayName = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "displayName")); + String colType = AppUtils.getRequestNvlValue(request, "colType"); + String displayFormat = AppUtils.getRequestNvlValue(request, "displayFormat"); + + //HYPERLINK + if(colType.equals(AppConstants.CT_HYPERLINK)) { + String hyperlinkURL = AppUtils.getRequestValue(request, "hyperlinkURL"); + currColumn.setHyperlinkURL(hyperlinkURL); + String anchor = AppUtils.getRequestValue(request, "anchor"); + currColumn.setHyperlinkType(anchor); + if(anchor.equals("IMAGE")) { + String actionImg = AppUtils.getRequestValue(request, "actionImg"); + currColumn.setActionImg(actionImg); + } + } + + + + String displayAlign = AppUtils.getRequestValue(request, "displayAlign"); + String displayHeaderAlign = AppUtils.getRequestValue(request, "displayHeaderAlign"); + String drillDownURL = AppUtils.getRequestValue(request, "drillDownURL"); + String drillDownSuppress = AppUtils.getRequestValue(request, "drillDownSuppress"); + boolean drillDownPopUp = AppUtils.getRequestFlag (request, "drillDownPopUp"); + String semaphoreId = AppUtils.getRequestNvlValue(request, "semaphore"); + String semaphoreType = AppUtils.getRequestNvlValue(request, "semaphoreTypeHidden"); + + String levelStr = AppUtils.getRequestNvlValue(request, "multiGroupColLevel"); + String startColGroup = AppUtils.getRequestNvlValue(request, "startMultiGroup"); + String colGroupColSpan = AppUtils.getRequestNvlValue(request, "colspan"); + int level = 0; + try { + level = Integer.parseInt(levelStr); + }catch (NumberFormatException ex) { + level = 0; + } + int startColGroupInt = 0; + int colGroupColSpanInt = 0; + if(level > 0) { + try { + //startColGroupInt = Integer.parseInt(startColGroup); + colGroupColSpanInt = Integer.parseInt(colGroupColSpan); + } catch (NumberFormatException ex) { + + } + } + currColumn.setLevel(level); + if(level > 0) { + currColumn.setStart(startColGroupInt); + currColumn.setColspan(colGroupColSpanInt); + } + + String targetColumnId = (semaphoreType.indexOf("|")!= -1 ? semaphoreType.substring(semaphoreType.indexOf("|")+1):""); + DataColumnType targetColumn = rdef.getColumnById(targetColumnId); + + SemaphoreType semaphore = rdef.getSemaphoreById(semaphoreId); + rdef.deleteSemaphore(semaphore); + if(nvl(semaphoreType).length() > 0 && semaphoreType.indexOf("|")!=-1) + semaphore.setSemaphoreType(semaphoreType.substring(0,semaphoreType.indexOf("|"))); + if(semaphore!=null) { + semaphore.setComment(currColumn.getColId()); + if(nvl(semaphoreType).length() > 0) + semaphore.setTarget(targetColumnId.length()>0? targetColumnId: ""); + rdef.setSemaphore(semaphore); + } + + + if (isEdit) { + if(nvl(widthInPxls).length()>0) { + if(nvl(widthInPxls).endsWith("px")) + currColumn.setDisplayWidthInPxls(widthInPxls); + else + currColumn.setDisplayWidthInPxls(widthInPxls+"px"); + } else { + currColumn.setDisplayWidthInPxls(""); + } + + currColumn.setCrossTabValue(crossTabValue); + currColumn.setDependsOnFormField(dependsOnFormField); + currColumn.setDisplayName(displayName); + //currColumn.setOriginalDisplayName(displayName); + + if (displayWidth > 0) + currColumn.setDisplayWidth(displayWidth); + currColumn.setDisplayAlignment(displayAlign); + currColumn.setDisplayHeaderAlignment(displayHeaderAlign); + currColumn.setDrillDownURL(drillDownURL); + currColumn.setDrillDownParams(drillDownParams); + currColumn.setDrillDownType(drillDownSuppress); + currColumn.setDrillinPoPUp(drillDownPopUp); + //indentation + currColumn.setIndentation(indentation); + if(drillDownPopUp) { + rdef.setDrillDownURLInPopupPresent(true); + } + /*if(targetColumn!=null) { + currColumn.setSemaphoreId(null); + targetColumn.setSemaphoreId(semaphoreId); + } else */ + currColumn.setSemaphoreId(semaphoreId); + currColumn.setGroupBreak(isGroupBreak); + logger.debug(EELFLoggerDelegate.debugLogger, (" ------------ Display Total ---------- "+ displayTotal)); + currColumn.setDisplayTotal(displayTotal); + //if (currColumn.getDrillDownURL() == null || currColumn.getDrillDownURL().length() == 0) + currColumn.setVisible(isVisible); + currColumn.setIsSortable(isSortable); + currColumn.setNowrap(nowrap); + //else + // currColumn.setVisible(true); + if (rdef.getReportDefType().equals(AppConstants.RD_SQL_BASED)) { + if(colType!=null) + currColumn.setColType(colType); + displayFormat = AppUtils.getRequestValue(request, "colDataFormat"); + if (displayFormat != null){ + currColumn.setColFormat(displayFormat); + } + if(colType!=null && colType.equals(AppConstants.CT_DATE)) { + boolean enhancedPagination = AppUtils.getRequestFlag(request, "enhancedPagination"); + currColumn.setEnhancedPagination(enhancedPagination); + } + } + if (!rdef.getReportDefType().equals(AppConstants.RD_SQL_BASED)) { + currColumn.setColName(colNameValue); + if (displayFormat != null) + currColumn.setColFormat(displayFormat); + //currColumn.setVisible(isVisible); + currColumn.setCalculated(exprFormula.length() > 0); + + rdef.adjustColumnType(currColumn); + } // if + + rdef.resetCache(true); + } else + currColumn = rdef.addDataColumnType(new ObjectFactory(), sColId, tableId, colName, + crossTabValue, colNameValue, displayName, displayWidth, displayAlign, rdef + .getAllColumns().size() + 1, isVisible, + (exprFormula.length() > 0), adjustDataType(dataType), displayFormat, + isGroupBreak, -1, null, displayTotal, null, -1, drillDownSuppress, + drillDownURL, drillDownParams, semaphoreId, null); + + if (rdef.getReportDefType().equals(AppConstants.RD_SQL_BASED)) + rdef.setColumnNoParseDateFlag(currColumn, AppUtils.getRequestFlag(request, + "no_parse_date")); + if(nvl(displayName).length()>0) + return true; + else + return false; + } // processColumnAddEdit + + private boolean processColumnAddMulti(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + List reportCols = rdef.getAllColumns(); + int nCol = reportCols.size() + 1; + + String[] addColumn = request.getParameterValues("addColumn"); + String[] tableId = request.getParameterValues("tableId"); + String[] columnName = request.getParameterValues("columnName"); + String[] columnType = request.getParameterValues("columnType"); + String[] displayName = request.getParameterValues("displayName"); + + for (int i = 0; i < addColumn.length; i++) + if (addColumn[i].equals("Y")) { + int j = 2; + String uniqueDisplayName = displayName[i]; + boolean isUnique = true; + do { + isUnique = true; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) + if (uniqueDisplayName.equals(((DataColumnType) iter.next()) + .getDisplayName())) { + isUnique = false; + uniqueDisplayName = displayName[i] + (j++); + break; + } // if + } while (!isUnique); + + rdef + .addDataColumnType( + new ObjectFactory(), + rdef.getUniqueColumnId(columnName[i]), + tableId[i], + columnName[i], + null, + columnName[i], + uniqueDisplayName, + 10, + "Left", + nCol++, + true, + false, + adjustDataType(columnType[i]), + (columnType[i].equals(AppConstants.CT_DATE) ? AppConstants.DEFAULT_DATE_FORMAT + : null), false, -1, null, null, null, -1, null, null, + null, null, null); + } // if + + return true; + } // processColumnAddMulti + + private boolean processColumnOrderAll(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String[] colId = request.getParameterValues("colId"); + String[] colOrder = request.getParameterValues("colOrder"); + + boolean reportUpdated = false; + for (int i = 0; i < colId.length; i++) { + DataColumnType dct = rdef.getColumnById(nvl(colId[i])); + if (dct == null) + continue; + + int iColOrder = 0; + try { + iColOrder = Integer.parseInt(colOrder[i]); + } catch (NumberFormatException e) { + } + + if (iColOrder > 0) { + dct.setOrderSeq(iColOrder); + reportUpdated = true; + } // if + } // for + + if (reportUpdated) { + List reportCols = rdef.getAllColumns(); + Collections.sort(reportCols, new OrderSeqComparator()); + + int iOrder = 1; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + dct.setOrderSeq(iOrder++); + } // for + + rdef.resetCache(false); + } // if + + return reportUpdated; + } // processColumnOrderAll + + private boolean processColumnDelete(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.deleteDataColumnType(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + return true; + } // processColumnDelete + + private boolean processColumnMoveUp(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.shiftColumnOrderUp(AppUtils + .getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + return true; + } // processColumnMoveUp + + private boolean processColumnMoveDown(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.shiftColumnOrderDown(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + return true; + } // processColumnMoveDown + + private boolean processFormFieldAddEdit(HttpServletRequest request, boolean isEdit, + String action) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String fieldName = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "fieldName")); + String multiSelectSize = "0"; + String colId = AppUtils.getRequestNvlValue(request, "fieldColId"); + if (rdef.getReportDefType().equals(AppConstants.RD_SQL_BASED)) { + String displayFormat = AppUtils.getRequestNvlValue(request, "displayFormat"); + if (displayFormat.length() > 0) + colId += "|" + displayFormat; + } // if + String fieldType = AppUtils.getRequestNvlValue(request, "fieldType"); + String validation = AppUtils.getRequestNvlValue(request, "validation"); + String mandatory = nvl(AppUtils.getRequestValue(request, "mandatory"), "N"); + String defaultValue = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "defaultValue")); + String fieldHelp = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "fieldHelp")); + String fieldSQL = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "fieldSQL")); + String fieldDefaultSQL = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "fieldDefaultSQL")); + String visible = nvl(AppUtils.getRequestValue(request, "visible"),"Y"); + String dependsOn = nvl(AppUtils.getRequestValue(request, "dependsOn"),""); + String rangeStartDate = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "rangeStartDate")); + String rangeEndDate = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "rangeEndDate")); + String rangeStartDateSQL = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "rangeStartDateSQL")); + String rangeEndDateSQL = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "rangeEndDateSQL")); + boolean isGroupFormField = AppUtils.getRequestFlag(request,"isGroupFormField"); + + Calendar start = null; + Calendar end = null; + if (AppUtils.nvl(rangeStartDate).length()>0){ + SimpleDateFormat dtf = new SimpleDateFormat("MM/dd/yyyy"); + start = Calendar.getInstance(); + start.setTime(dtf.parse(rangeStartDate)); + } + if (AppUtils.nvl(rangeEndDate).length()>0){ + SimpleDateFormat dtf = new SimpleDateFormat("MM/dd/yyyy"); + end = Calendar.getInstance(); + end.setTime(dtf.parse(rangeEndDate)); + }/* + * if(fieldHelp.length()>255) fieldHelp = fieldHelp.substring(0, 255); + */ + + boolean reportUpdated = false; + + FormFieldType currField = null; + if (isEdit) { + String fieldId = AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID); + + currField = rdef.getFormFieldById(fieldId); + if (currField != null && nvl(fieldName).length()>0) { + reportUpdated = (!(fieldName.equals(nvl(currField.getFieldName())) + && colId.equals(nvl(currField.getColId())) + && fieldType.equals(nvl(currField.getFieldType())) + && validation.equals(nvl(currField.getValidationType())) + && mandatory.equals(nvl(currField.getMandatory(), "N")) + && defaultValue.equals(nvl(currField.getDefaultValue())) + && fieldSQL.equals(nvl(currField.getFieldSQL())) + && fieldDefaultSQL.equals(nvl(currField.getFieldDefaultSQL())) + && dependsOn.equals(nvl(currField.getDependsOn(), "N")) + && (start == null || (start != null && currField.getRangeStartDate() == null) || (start.equals(currField.getRangeStartDate()))) + && (end == null || (end != null && currField.getRangeEndDate() == null) || (end.equals(currField.getRangeEndDate()))) + && rangeStartDateSQL.equals(nvl(currField.getRangeStartDateSQL())) + && rangeEndDateSQL.equals(nvl(currField.getRangeEndDateSQL())) + && visible.equals(nvl(currField.getVisible(), "Y")) + && isGroupFormField == currField.isGroupFormField() + && fieldHelp.equals(nvl(currField.getComment())))); + + rdef.replaceFormFieldReferences("[" + currField.getFieldName() + "]", "[" + + fieldName + "]"); + + currField.setFieldName(fieldName); + currField.setColId(colId); + currField.setFieldType(fieldType); + currField.setValidationType(validation); + currField.setMandatory(mandatory); + currField.setDefaultValue(defaultValue); + currField.setFieldSQL(fieldSQL); + currField.setFieldDefaultSQL(fieldDefaultSQL); + currField.setComment(fieldHelp); + currField.setVisible(visible); + currField.setDependsOn(dependsOn); + try { + if(start!=null) { + currField.setRangeStartDate(DatatypeFactory.newInstance() + .newXMLGregorianCalendar(start.YEAR, start.MONTH, start.DAY_OF_WEEK, start.HOUR, start.MINUTE, start.SECOND, start.MILLISECOND, start.ZONE_OFFSET)); + } else { + currField.setRangeStartDate(null); + } + if(end!=null) { + currField.setRangeEndDate(DatatypeFactory.newInstance() + .newXMLGregorianCalendar(end.YEAR, end.MONTH, end.DAY_OF_WEEK, end.HOUR, end.MINUTE, end.SECOND, end.MILLISECOND, end.ZONE_OFFSET)); + } else { + currField.setRangeEndDate(null); + } + /*currField.setRangeEndDate(DatatypeFactory.newInstance() + .newXMLGregorianCalendar(end));*/ + } catch (DatatypeConfigurationException ex) { + + } + + currField.setRangeStartDateSQL(rangeStartDateSQL); + currField.setRangeEndDateSQL(rangeEndDateSQL); + currField.setGroupFormField(isGroupFormField); + if(fieldType.equals(FormField.FFT_LIST_MULTI)) { + multiSelectSize = AppUtils.getRequestNvlValue(request, "multiSelectListSize"); + currField.setMultiSelectListSize(multiSelectSize); + } + + + } // if + } else { + reportUpdated = true; + + currField = rdef.addFormFieldType(new ObjectFactory(), fieldName, colId, + fieldType, validation, mandatory, defaultValue, fieldSQL, fieldHelp, start, end, rangeStartDateSQL, rangeEndDateSQL); + + request.setAttribute(AppConstants.RI_DETAIL_ID, currField.getFieldId()); + } // else + + if (action.equals(AppConstants.WA_ADD_USER)) { + reportUpdated = true; + rdef.addFormFieldPredefinedValue(new ObjectFactory(), currField, XSSFilter.filterRequestOnlyScript(AppUtils + .getRequestNvlValue(request, "newPredefinedValue"))); + } else if (action.equals(AppConstants.WA_DELETE_USER)) { + reportUpdated = true; + rdef.deleteFormFieldPredefinedValue(currField, AppUtils.getRequestNvlValue( + request, "delPredefinedValue")); + } + + return reportUpdated; + } // processFormFieldAddEdit + + private boolean processFormFieldDelete(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String fieldId = AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID); + rdef.deleteFormField(fieldId); + + return true; + } // processFormFieldDelete + + private boolean processFormFieldMoveUp(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.shiftFormFieldUp(AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + return true; + } // processFormFieldMoveUp + + private boolean processFormFieldMoveDown(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.shiftFormFieldDown(AppUtils + .getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + return true; + } // processFormFieldMoveDown + + private boolean processFormFieldBlank(HttpServletRequest request) throws Exception { + boolean reportUpdated = false; + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + reportUpdated = true; + rdef.addFormFieldBlank(new ObjectFactory()); + return true; + } // processFormFieldMoveDown + + //processFormFieldInfoBar + private boolean processFormFieldInfoBar(HttpServletRequest request) throws Exception { + boolean reportUpdated = false; + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + reportUpdated = true; + rdef.addCustomizedTextForParameters(XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "blueBarField"))); + return true; + } // processFormFieldMoveDown + + + private boolean processForecasting(HttpServletRequest request, String action) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + if(rdef.getDataminingOptions()==null) + rdef.addDataminingOptions(new ObjectFactory()); + + String classifiers = AppUtils.getRequestNvlValue(request, "classifiers"); + rdef.setClassifier(classifiers); + String dateAttrColId = AppUtils.getRequestNvlValue(request, "timeAttribute"); + String timeFormat = AppUtils.getRequestNvlValue(request, "timeFormat"); + if(timeFormat.equals("Default")) timeFormat = "yyyy-MM-dd HH:mm:ss"; + String forecastingPeriod = AppUtils.getRequestNvlValue(request, "forecastingPeriod"); + + String[] forecastCols = request.getParameterValues("forecastCol"); + List reportCols = rdef.getAllColumns(); + DataColumnType dct = null; + Iterator iter = null; + + + + if(dateAttrColId != null) { + for(iter=reportCols.iterator(); iter.hasNext(); ) { + dct = (DataColumnType) iter.next(); + if(dct.getColId().equals(dateAttrColId)) { + dct.setDataMiningCol(AppConstants.DM_DATE_ATTR); + if(timeFormat!=null) rdef.setForecastingTimeFormat(timeFormat); + break; + } + } + } + + if(forecastCols != null) { + for (int i = 0; i < forecastCols.length; i++) { + for(iter=reportCols.iterator(); iter.hasNext(); ) { + dct = (DataColumnType) iter.next(); + if(dct.getColId().equals(forecastCols[i])) { + dct.setDataMiningCol(AppConstants.DM_FORECASTING_ATTR); + } + } + } + rdef.setForecastingPeriod(forecastingPeriod); + } + boolean reportUpdated = true; + + return reportUpdated; + } // processForecasting + + + private boolean processFilterAddEdit(HttpServletRequest request, boolean isEdit) + throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String colId = AppUtils.getRequestNvlValue(request, "filterColId"); + String filterExpr = AppUtils.getRequestNvlValue(request, "filterExpr"); + String argType = (filterExpr.equals("IS NULL") || filterExpr.equals("IS NOT NULL")) ? null + : AppUtils.getRequestNvlValue(request, "argType"); + String argValue = (filterExpr.equals("IS NULL") || filterExpr.equals("IS NOT NULL")) ? null + : AppUtils.getRequestNvlValue(request, "argValue"); + + if (nvl(argType).equals(AppConstants.AT_COLUMN)) { + List reportCols = rdef.getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + if (argValue.equals("[" + dct.getDisplayName() + "]")) { + argValue = dct.getColId(); + break; + } + } // for + } // if + + if (nvl(argType).equals(AppConstants.AT_VALUE) + && (!nvl(argValue).equals(AppConstants.FILTER_MAX_VALUE)) + && (!nvl(argValue).equals(AppConstants.FILTER_MIN_VALUE))) { + // Validating the value by type + DataColumnType currColumn = rdef.getColumnById(colId); + String currColType = currColumn.getColType(); + + try { + String s_sql = Globals.getProcessFilterAddEdit(); + s_sql = s_sql.replace("[argValue]", argValue); + /*DataSet ds = DbUtils.executeQuery("SELECT " + + (currColType.equals(AppConstants.CT_NUMBER) ? ("TO_NUMBER('" + + argValue + "')") + : (currColType.equals(AppConstants.CT_DATE) ? ("TO_DATE('" + + argValue + + "', '" + + nvl(currColumn.getColFormat(), + AppConstants.DEFAULT_DATE_FORMAT) + "')") + : ("'" + argValue + "'"))) + " FROM dual");*/ + + DataSet ds = DbUtils.executeQuery("SELECT " + + (currColType.equals(AppConstants.CT_NUMBER) ? ("TO_NUMBER('" + + argValue + "')") + : (currColType.equals(AppConstants.CT_DATE) ? ("TO_DATE('" + + argValue + + "', '" + + nvl(currColumn.getColFormat(), + AppConstants.DEFAULT_DATE_FORMAT) + "')") + : s_sql))); + } catch (Exception e) { + throw new ValidationException( + "" + + (currColType.equals(AppConstants.CT_NUMBER) ? "Invalid number" + : (currColType.equals(AppConstants.CT_DATE) ? ("Invalid date
Expected date format " + nvl( + currColumn.getColFormat(), + AppConstants.DEFAULT_DATE_FORMAT)) + : "Invalid value
Possible reason: use of single quotes")) + + "
Value: " + argValue); + } + } // if + + if (isEdit) { + int filterPos = -1; + try { + filterPos = Integer.parseInt(AppUtils.getRequestValue(request, "filterPos")); + } catch (NumberFormatException e) { + } + + ColFilterType currFilter = rdef.getFilterById(colId, filterPos); + if (currFilter != null) { + currFilter.setJoinCondition(AppUtils.getRequestValue(request, "filterJoin")); + currFilter.setOpenBrackets(AppUtils.getRequestValue(request, "openBrackets")); + currFilter.setExpression(filterExpr); + // if(argType!=null) + currFilter.setArgType(argType); + // if(argValue!=null) + currFilter.setArgValue(argValue); + currFilter + .setCloseBrackets(AppUtils.getRequestValue(request, "closeBrackets")); + } // if + + rdef.resetCache(true); + } else { + rdef.addColFilterType(new ObjectFactory(), colId, AppUtils.getRequestValue( + request, "filterJoin"), AppUtils.getRequestValue(request, "openBrackets"), + filterExpr, argType, argValue, AppUtils.getRequestValue(request, + "closeBrackets"), null); + } // else + + return true; + } // processFilterAddEdit + + private boolean processFilterDelete(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String filterId = AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID); + String colId = filterId.substring(0, filterId.indexOf('|')); + int filterPos = -1; + try { + filterPos = Integer.parseInt(filterId.substring(colId.length() + 1)); + } catch (NumberFormatException e) { + } + + rdef.removeColumnFilter(colId, filterPos); + + return true; + } // processFilterDelete + + private boolean processSortAddEdit(HttpServletRequest request, boolean isEdit) + throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String sortAscDesc = AppUtils.getRequestNvlValue(request, "sortAscDesc"); + if (isEdit) { + DataColumnType currColumn = rdef.getColumnById(AppUtils.getRequestNvlValue( + request, AppConstants.RI_DETAIL_ID)); + if (currColumn != null) + currColumn.setOrderByAscDesc(sortAscDesc); + rdef.resetCache(true); + } else + rdef.addColumnSort(AppUtils.getRequestNvlValue(request, "sortColId"), sortAscDesc, + rdef.getNumSortColumns() + 1); + + return true; + } // processSortAddEdit + + private boolean processSortOrderAll(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String[] colId = request.getParameterValues("colId"); + String[] sortOrder = request.getParameterValues("sortOrder"); + String[] sortAscDesc = request.getParameterValues("sortAscDesc"); + + boolean reportUpdated = false; + for (int i = 0; i < colId.length; i++) { + DataColumnType dct = rdef.getColumnById(nvl(colId[i])); + if (dct == null) + continue; + + int iSortOrder = 0; + try { + iSortOrder = Integer.parseInt(sortOrder[i]); + } catch (NumberFormatException e) { + } + + if (iSortOrder > 0) { + if (dct.getOrderBySeq() > 0) { + // Update sort + if (dct.getOrderBySeq() != iSortOrder) { + dct.setOrderBySeq(iSortOrder); + reportUpdated = true; + } // if + if (!nvl(dct.getOrderByAscDesc()).equals(nvl(sortAscDesc[i]))) { + dct.setOrderByAscDesc(sortAscDesc[i]); + reportUpdated = true; + } // if + } else { + // Add sort + dct.setOrderBySeq(iSortOrder); + dct.setOrderByAscDesc(sortAscDesc[i]); + reportUpdated = true; + } // else + } else { + if (dct.getOrderBySeq() > 0) { + // Remove sort + dct.setOrderBySeq(0); + dct.setOrderByAscDesc(null); + reportUpdated = true; + } // if + } // else + } // for + + if (reportUpdated) { + List reportCols = rdef.getAllColumns(); + Collections.sort(reportCols, new OrderBySeqComparator()); + int iOrder = 1; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + if (dct.getOrderBySeq() > 0) + dct.setOrderBySeq(iOrder++); + } // for + Collections.sort(reportCols, new OrderSeqComparator()); + + rdef.resetCache(true); + } // if + + return reportUpdated; + } // processSortOrderAll + + private boolean processSortDelete(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.removeColumnSort(AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + return true; + } // processSortDelete + + private boolean processSortMoveUp(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef + .shiftColumnSortUp(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + return true; + } // processSortMoveUp + + private boolean processSortMoveDown(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.shiftColumnSortDown(AppUtils.getRequestNvlValue(request, + AppConstants.RI_DETAIL_ID)); + return true; + } // processSortMoveDown + + private boolean processJavascript (HttpServletRequest request) throws Exception { + processSaveJavascriptElement(request); + return true; + } + + private boolean processSaveJavascriptElement (HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + rdef.setJavascriptElement(AppUtils.getRequestNvlValue(request, AppConstants.RI_JAVASCRIPT)); + String id = AppUtils.getRequestNvlValue(request, AppConstants.RI_JAVASCRIPT_ITEM_ID); + String fieldId = AppUtils.getRequestNvlValue(request, "javascriptFormField-"+id); + if( nvl(fieldId).length()>0 && !(fieldId.startsWith("-1"))) { + + String callableJavascriptText = AppUtils.getRequestNvlValue(request, "callText-"+id); + + logger.debug(EELFLoggerDelegate.debugLogger, ("FieldId " + fieldId + " Call Text " + callableJavascriptText+ " id " + id)); + JavascriptItemType javaScriptType = null; + if(id.length()>0 && id.startsWith("-1")) { + javaScriptType = rdef.addJavascriptType(new ObjectFactory(), id); + javaScriptType.setFieldId(fieldId); + if(!fieldId.equals("os1") || !fieldId.equals("ol1")) + javaScriptType.setId(rdef.getNextIdForJavaScriptElement(new ObjectFactory(), fieldId)); + else { + if(fieldId.equals("os1")) + javaScriptType.setId("os1|1"); + else + javaScriptType.setId("ol1|1"); + } + javaScriptType.setCallText(callableJavascriptText); + } else { + javaScriptType = rdef.addJavascriptType(new ObjectFactory(), id); + javaScriptType.setCallText(callableJavascriptText); + } + } + return true; + } + private boolean processAddJavascriptElement (HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + JavascriptItemType javaScriptType = rdef.addJavascriptType(new ObjectFactory(), ""); + javaScriptType.setId(""); + javaScriptType.setFieldId(""); + javaScriptType.setCallText(""); + + return true; + } + + private boolean processDeleteJavascriptElement (HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + String id = AppUtils.getRequestNvlValue(request, AppConstants.RI_JAVASCRIPT_ITEM_ID); + if(rdef.deleteJavascriptType(id)) + return true; + else + return false; + } + + private boolean processChart(HttpServletRequest request, String action) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + int valueColsCount = rdef.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null).size(); + + String chartType = AppUtils.getRequestNvlValue(request, "chartType"); + String chartTypeFixed = AppUtils.getRequestValue(request, "chartTypeFixed"); + String legendColId = AppUtils.getRequestNvlValue(request, "legendCol"); + // String valueColId = AppUtils.getRequestNvlValue(request, "valueCol"); + String leftAxisLabel = AppUtils.getRequestValue(request, "leftAxisLabel"); + String rightAxisLabel = AppUtils.getRequestValue(request, "rightAxisLabel"); + String chartWidth = XSSFilter.filterRequest(AppUtils.getRequestNvlValue(request, "chartWidth")); + String chartHeight = XSSFilter.filterRequest(AppUtils.getRequestNvlValue(request, "chartHeight")); + String chartMultiseries = AppUtils.getRequestNvlValue(request, "multiSeries"); + String lastSeriesALineChart = AppUtils.getRequestNvlValue(request, "lastSeriesALineChart"); + String lastSeriesABarChart = AppUtils.getRequestNvlValue(request, "lastSeriesABarChart"); + String overLayItemLabel = "N"; + String chartDisplay = null; + + String multiplePieOrder = null; + String multiplePieLabelDisplay = null; + + String chartOrientation = null; + String secondaryChartRenderer = null; + + String linearRegression = null; + + boolean multiplePieOrderInRunPage = false; + boolean multiplePieLabelDisplayInRunPage = false; + + boolean chartOrientationInRunPage = false; + boolean secondaryChartRendererInRunPage = false; + + boolean chartDisplayInRunPage = false; + + String intervalFromdate = null; + String intervalTodate = null; + String intervalLabel = null; + boolean displayIntervalInputInRunPage = false; + boolean animate = false; + + animate = AppUtils.getRequestNvlValue(request, "animatedOption").equals("animate"); + if(Globals.showAnimatedChartOption()) + rdef.setChartAnimate(animate); + + + String removeColId = ""; + if (action.equals(AppConstants.WA_DELETE_USER)) { + removeColId = AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID); + if(valueColsCount == 2 && !rdef.hasSeriesColumn()) { + rdef.setChartLeftAxisLabel(null); + rdef.setChartRightAxisLabel(null); + + if(chartType.equals(AppConstants.GT_TIME_SERIES) || chartType.equals(AppConstants.GT_PIE_MULTIPLE)) { + chartMultiseries = "N"; + } + } + } + + if(rdef.getChartAdditionalOptions()==null) + rdef.addChartAdditionalOptions(new ObjectFactory()); + + if(rdef.getChartDrillOptions()==null) + rdef.addChartDrillOptions(new ObjectFactory()); + + //clearing already added + if(rdef.getChartDrillOptions().getTargetFormfield()!=null) + rdef.getChartDrillOptions().getTargetFormfield().removeAll(rdef.getChartDrillOptions().getTargetFormfield()); + + + if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) { + multiplePieOrder = AppUtils.getRequestNvlValue(request, "multiplePieOrder"); + multiplePieLabelDisplay = AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"); + chartDisplay = AppUtils.getRequestNvlValue(request, "chartDisplay"); + //if(AppUtils.getRequestNvlValue(request, "multiplePieOrderInRunPage").length()>0) + multiplePieOrderInRunPage = AppUtils.getRequestNvlValue(request,"multiplePieOrderInRunPage").equals("Y"); + //if(AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplayInRunPage").length()>0) + multiplePieLabelDisplayInRunPage = AppUtils.getRequestNvlValue(request,"multiplePieLabelDisplayInRunPage").equals("Y"); + //if(AppUtils.getRequestNvlValue(request, "chartDisplayInRunPage").length()>0) + chartDisplayInRunPage = AppUtils.getRequestNvlValue(request,"chartDisplayInRunPage").equals("Y"); + if(rdef.getChartAdditionalOptions()!=null) { + rdef.setChartMultiplePieOrder(multiplePieOrder+(multiplePieOrderInRunPage?"|Y":"")); + rdef.setChartMultiplePieLabelDisplay(multiplePieLabelDisplay+(multiplePieLabelDisplayInRunPage?"|Y":"")); + rdef.setChartDisplay(chartDisplay+(chartDisplayInRunPage?"|Y":"")); + } + + } + + if(chartType.equals(AppConstants.GT_REGRESSION)) { + linearRegression = AppUtils.getRequestNvlValue(request, "regressionType"); + rdef.setLinearRegressionColor(AppUtils.getRequestNvlValue(request, "valueLinearRegressionColor")); + rdef.setExponentialRegressionColor(AppUtils.getRequestNvlValue(request, "valueExponentialRegressionColor")); + rdef.setCustomizedRegressionPoint(AppUtils.getRequestNvlValue(request, "regressionPointCustomization")); + + if(nvl(linearRegression).length()>0) + rdef.setLinearRegression(linearRegression); + else + rdef.setLinearRegression("Y"); + } + + if(chartType.equals(AppConstants.GT_BAR_3D)) { + chartOrientation = AppUtils.getRequestNvlValue(request, "chartOrientation"); + secondaryChartRenderer = AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"); + chartDisplay = AppUtils.getRequestNvlValue(request, "chartDisplay"); + //if(AppUtils.getRequestNvlValue(request, "chartOrientationInRunPage").length()>0) + chartOrientationInRunPage = AppUtils.getRequestNvlValue(request,"chartOrientationInRunPage").equals("Y"); + //if(AppUtils.getRequestNvlValue(request, "secondaryChartRendererInRunPage").length()>0) + secondaryChartRendererInRunPage = AppUtils.getRequestNvlValue(request,"secondaryChartRendererInRunPage").equals("Y"); + //if(AppUtils.getRequestNvlValue(request, "chartDisplayInRunPage").length()>0) + chartDisplayInRunPage = AppUtils.getRequestNvlValue(request,"chartDisplayInRunPage").equals("Y"); + rdef.setChartOrientation(chartOrientation+(chartOrientationInRunPage?"|Y":"")); + rdef.setSecondaryChartRenderer(secondaryChartRenderer+(secondaryChartRendererInRunPage?"|Y":"")); + rdef.setChartDisplay(chartDisplay+(chartDisplayInRunPage?"|Y":"")); + rdef.setLastSeriesALineChart(nvl(lastSeriesALineChart, "N")); + } + + if(chartType.equals(AppConstants.GT_LINE)) { + chartOrientation = AppUtils.getRequestNvlValue(request, "chartOrientation"); + secondaryChartRenderer = AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"); + chartDisplay = AppUtils.getRequestNvlValue(request, "chartDisplay"); + //if(AppUtils.getRequestNvlValue(request, "chartOrientationInRunPage").length()>0) + chartOrientationInRunPage = AppUtils.getRequestNvlValue(request,"chartOrientationInRunPage").equals("Y"); + //if(AppUtils.getRequestNvlValue(request, "secondaryChartRendererInRunPage").length()>0) + secondaryChartRendererInRunPage = AppUtils.getRequestNvlValue(request,"secondaryChartRendererInRunPage").equals("Y"); + //if(AppUtils.getRequestNvlValue(request, "chartDisplayInRunPage").length()>0) + chartDisplayInRunPage = AppUtils.getRequestNvlValue(request,"chartDisplayInRunPage").equals("Y"); + rdef.setChartOrientation(chartOrientation+(chartOrientationInRunPage?"|Y":"")); + rdef.setSecondaryChartRenderer(secondaryChartRenderer+(secondaryChartRendererInRunPage?"|Y":"")); + rdef.setChartDisplay(chartDisplay+(chartDisplayInRunPage?"|Y":"")); + rdef.setLastSeriesABarChart(nvl(lastSeriesABarChart, "N")); + } + if(chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) { + intervalFromdate = AppUtils.getRequestNvlValue(request, "intervalFromDate"); + intervalTodate = AppUtils.getRequestNvlValue(request, "intervalToDate"); + intervalLabel = AppUtils.getRequestNvlValue(request, "intervalLabel"); + displayIntervalInputInRunPage = AppUtils.getRequestNvlValue(request,"intervalInputInRunPage").equals("Y"); + rdef.setIntervalFromdate(intervalFromdate+(displayIntervalInputInRunPage?"|Y":"")); + rdef.setIntervalTodate(intervalTodate+(displayIntervalInputInRunPage?"|Y":"")); + rdef.setIntervalLabel(intervalLabel); + } + if(chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES) + || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)) { + overLayItemLabel = AppUtils.getRequestNvlValue(request, "overlayItemValue"); + rdef.setOverlayItemValueOnStackBar(nvl(overLayItemLabel, "N")); + animate = AppUtils.getRequestNvlValue(request, "animatedOption").equals("animate"); + rdef.setChartAnimate(animate); + } + + rdef.setRangeAxisLowerLimit(AppUtils.getRequestNvlValue(request, "yAxisLowerLimit")); + rdef.setRangeAxisUpperLimit(AppUtils.getRequestNvlValue(request, "yAxisUpperLimit")); + rdef.setLegendLabelAngle(AppUtils.getRequestNvlValue(request,"labelAngle")); + rdef.setLegendPosition(AppUtils.getRequestNvlValue(request,"legendPosition")); + rdef.setMaxLabelsInDomainAxis(AppUtils.getRequestNvlValue(request,"maxLabelsInDomainAxis")); + String chartLegendDisplay = AppUtils.getRequestNvlValue(request,"hideLegend"); + boolean showLegendDisplayOptionsInRunPage = false; + showLegendDisplayOptionsInRunPage = AppUtils.getRequestNvlValue(request,"showLegendDisplayOptionsInRunPage").equals("Y"); + rdef.setChartLegendDisplay(chartLegendDisplay+(showLegendDisplayOptionsInRunPage?"|Y":"")); + rdef.setChartToolTips(AppUtils.getRequestNvlValue(request,"hideTooltips")); + rdef.setDomainAxisValuesAsString(AppUtils.getRequestNvlValue(request,"keepAsString")); + + //System.out.println("KeepAsString " + AppUtils.getRequestNvlValue(request,"keepAsString")); + //System.out.println("From ReportDef " + rdef.keepDomainAxisValueInChartAsString()); + // boolean reportUpdated = (! + // chartType.equals(nvl(rdef.getChartType()))); + rdef.setChartType(chartType); + rdef.setChartTypeFixed(nvl(chartTypeFixed, "N")); + if (nvl(leftAxisLabel).length()>0) + rdef.setChartLeftAxisLabel(leftAxisLabel); + else + rdef.setChartLeftAxisLabel(null); + if (nvl(rightAxisLabel).length()>0) + rdef.setChartRightAxisLabel(rightAxisLabel); + else + rdef.setChartRightAxisLabel(null); + rdef.setChartWidth(nvl(chartWidth, "" + Globals.getDefaultChartWidth())); + rdef.setChartHeight(nvl(chartHeight, "" + Globals.getDefaultChartHeight())); + if(chartType.equals(AppConstants.GT_TIME_SERIES) || chartType.equals(AppConstants.GT_PIE_MULTIPLE)) { + rdef.setChartMultiSeries(chartMultiseries); + } else { + rdef.setChartMultiSeries("N"); + } + + List reportCols = rdef.getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (dct.getColId().equals(legendColId)) { + // reportUpdated = reportUpdated||(! + // nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)); + dct.setColOnChart(AppConstants.GC_LEGEND); + } else { + // reportUpdated = + // reportUpdated||nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND); + dct.setColOnChart(null); + } + + /* + * if(dct.getColId().equals(valueColId)) { reportUpdated = + * reportUpdated||(dct.getChartSeq()<=0); dct.setChartSeq(1); } + * else { reportUpdated = reportUpdated||(dct.getChartSeq()>0); + */ + dct.setChartSeq(-1); + /* } */ + } // for + + int idx = 1; + List columns = rdef.getAllColumns(); + if(chartType.equals(AppConstants.GT_TIME_SERIES)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + String chartGroup = AppUtils.getRequestNvlValue(request, "chartGroup"); + String yAxis = AppUtils.getRequestNvlValue(request, "yAxis"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + + String drillDownReportId = AppUtils.getRequestNvlValue(request, "drillDownReport"); + if(!drillDownReportId.equals("-1")) { + ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, drillDownReportId, + false); + if (ddRr != null) + request.setAttribute("CHART_FORMFIELDS", ddRr.getReportFormFields()); + + for(ddRr.getReportFormFields().resetNext(); ddRr.getReportFormFields().hasNext(); ) { + FormField ff = ddRr.getReportFormFields().getNext(); + if(!ff.getFieldType().equals(FormField.FFT_BLANK)) { + String value = AppUtils.getRequestNvlValue(request, "drillDown_"+ff.getFieldName()); + ChartDrillFormfield cdf = new ObjectFactory().createChartDrillFormfield(); + cdf.setFormfield(value); + rdef.getChartDrillOptions().getTargetFormfield().add(cdf); + } + } + } + + } else { + if(chartType.equals(AppConstants.GT_BAR_3D)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + String chartGroup = AppUtils.getRequestNvlValue(request, "chartGroup"); + String yAxis = AppUtils.getRequestNvlValue(request, "yAxis"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + String drillDownReportId = AppUtils.getRequestNvlValue(request, "drillDownReport"); + rdef.setDrillReportIdForChart(drillDownReportId); + if(drillDownReportId.equals("-1")){ + rdef.setDrillReportIdForChart(""); + } + + if(!drillDownReportId.equals("-1")) { + ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, drillDownReportId, + false); + if (ddRr != null) + request.setAttribute("CHART_FORMFIELDS", ddRr.getReportFormFields()); + + for(ddRr.getReportFormFields().resetNext(); ddRr.getReportFormFields().hasNext(); ) { + FormField ff = ddRr.getReportFormFields().getNext(); + if(!ff.getFieldType().equals(FormField.FFT_BLANK)) { + String value = AppUtils.getRequestNvlValue(request, "drillDown_"+ff.getFieldName()); + ChartDrillFormfield cdf = new ObjectFactory().createChartDrillFormfield(); + cdf.setFormfield(value); + rdef.getChartDrillOptions().getTargetFormfield().add(cdf); + } + } + + String xAxisFormField = AppUtils.getRequestNvlValue(request, "drillDownXAxisFormfield"); + String yAxisFormField = AppUtils.getRequestNvlValue(request, "drillDownYAxisFormfield"); + String seriesAxisFormField = AppUtils.getRequestNvlValue(request, "drillDownSeriesAxisFormfield"); + + if(!xAxisFormField.equals("-1")){ + rdef.setDrillXAxisFormField(xAxisFormField); + + if(!yAxisFormField.equals("-1")) + rdef.setDrillYAxisFormField(yAxisFormField); + if(!seriesAxisFormField.equals("-1")) + rdef.setDrillSeriesFormField(seriesAxisFormField); + } else { + rdef.setDrillXAxisFormField(""); + rdef.setDrillYAxisFormField(""); + rdef.setDrillSeriesFormField(""); + } + } + + } else if(chartType.equals(AppConstants.GT_SCATTER)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + + }else if(chartType.equals(AppConstants.GT_REGRESSION)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + }else if(chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) + || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + }else if(chartType.equals(AppConstants.GT_LINE)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + } else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + } else if (chartType.equals(AppConstants.GT_COMPARE_PREVYEAR_CHART)) { + String chartSeries = AppUtils.getRequestNvlValue(request, "chartSeries"); + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + //debugLogger.debug("**********In " + chartSeries + " " + alldct.getColId()); + alldct.setChartSeries((chartSeries.equals(alldct.getColId()))?true : false); + } + + } else { + if (rdef.hasSeriesColumn()) { + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType alldct = (DataColumnType) iterator.next(); + alldct.setChartSeries(false); + } + } + + String drillDownReportId = AppUtils.getRequestNvlValue(request, "drillDownReport"); + rdef.setDrillReportIdForChart(drillDownReportId); + if(drillDownReportId.equals("-1")){ + rdef.setDrillReportIdForChart(""); + } + + if(!drillDownReportId.equals("-1")) { + ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, drillDownReportId, + false); + if (ddRr != null) + request.setAttribute("CHART_FORMFIELDS", ddRr.getReportFormFields()); + for(ddRr.getReportFormFields().resetNext(); ddRr.getReportFormFields().hasNext(); ) { + FormField ff = ddRr.getReportFormFields().getNext(); + if(!ff.getFieldType().equals(FormField.FFT_BLANK)) { + String value = AppUtils.getRequestNvlValue(request, "drillDown_"+ff.getFieldName()); + ChartDrillFormfield cdf = new ObjectFactory().createChartDrillFormfield(); + cdf.setFormfield(value); + rdef.getChartDrillOptions().getTargetFormfield().add(cdf); + } + } + + String xAxisFormField = AppUtils.getRequestNvlValue(request, "drillDownXAxisFormfield"); + String yAxisFormField = AppUtils.getRequestNvlValue(request, "drillDownYAxisFormfield"); + String seriesAxisFormField = AppUtils.getRequestNvlValue(request, "drillDownSeriesAxisFormfield"); + + if(!xAxisFormField.equals("-1")){ + rdef.setDrillXAxisFormField(xAxisFormField); + + if(!yAxisFormField.equals("-1")) + rdef.setDrillYAxisFormField(yAxisFormField); + if(!seriesAxisFormField.equals("-1")) + rdef.setDrillSeriesFormField(seriesAxisFormField); + } else { + rdef.setDrillXAxisFormField(""); + rdef.setDrillYAxisFormField(""); + rdef.setDrillSeriesFormField(""); + } + } + + } + } + + for (int i = 1; i < Math.max(valueColsCount, 1) + 1; i++) { + //debugLogger.debug("********** " + chartSeries); + if(i==1) { + /* Range Axis is resetted before adding */ + for (Iterator iterator = columns.iterator(); iterator.hasNext();) { + DataColumnType dct = (DataColumnType) iterator.next(); + if(!nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) { + dct.setChartSeq(-1); + dct.setChartColor(null); + dct.setColOnChart(null); + dct.setCreateInNewChart(false); + dct.setChartGroup(null); + dct.setYAxis(null); + } + } + + } + String newChartColAxis = AppUtils.getRequestNvlValue(request, "newChart" + i+"Axis"); + String valueColId = AppUtils.getRequestNvlValue(request, "valueCol" + i); + String valueColColor = AppUtils.getRequestNvlValue(request, "valueCol" + i + + "Color"); + String valueColAxis = AppUtils + .getRequestNvlValue(request, "valueCol" + valueColId + "Axis"); + String chartGroup = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "chartGroup" + valueColId + "Axis")); + String yAxisGroup = ""; + yAxisGroup = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "YAxisLabel" + valueColId)); + //debugLogger.debug("^^^^^^^^^^^^^^^^^Chart Group " + chartGroup); + //if(chartType.equals(AppConstants.GT_TIME_SERIES)) { + // debugLogger.debug("**********Outer If " + chartSeries); + //} + + if (valueColId.length() > 0 && (!valueColId.equals(removeColId))) { + DataColumnType dct = rdef.getColumnById(valueColId); + dct.setChartSeq(idx++); + dct.setChartColor(valueColColor); + dct.setColOnChart(valueColAxis.equals("Y") ? "1" : "0"); + if(chartType.equals(AppConstants.GT_TIME_SERIES)) { + dct.setCreateInNewChart(newChartColAxis.equals("Y") ? true : false); + } else + dct.setCreateInNewChart(false); + + if(chartGroup!=null && chartGroup.length()>0) + dct.setChartGroup(chartGroup+"|"+valueColId); + else dct.setChartGroup(""); + if(chartType.equals(AppConstants.GT_TIME_SERIES)) + dct.setYAxis(nvl(yAxisGroup)+"|"+valueColId); + else if (chartType.equals(AppConstants.GT_BAR_3D)) + dct.setYAxis(nvl(yAxisGroup)+"|"+valueColId); + else dct.setYAxis(""); + //} + //else + //dct.setCreateInNewChart(false); + } else if (valueColId.length() > 0 && (valueColId.equals(removeColId))) {// if + DataColumnType dct = rdef.getColumnById(valueColId); + dct.setChartSeq(-1); + dct.setChartColor(null); + dct.setColOnChart(null); + dct.setCreateInNewChart(false); + dct.setChartGroup(null); + dct.setYAxis(null); + } else { // else + DataColumnType dct = rdef.getColumnById(valueColId); + dct.setChartSeq(-1); + dct.setChartColor(null); + dct.setColOnChart(null); + dct.setCreateInNewChart(false); + dct.setChartGroup(null); + dct.setYAxis(null); + } + } // for + + if (action.equals(AppConstants.WA_ADD_USER)) { + String valueColId = AppUtils.getRequestNvlValue(request, "valueColNew"); + String valueColColor = AppUtils.getRequestNvlValue(request, "valueColNewColor"); + String valueColAxis = AppUtils.getRequestNvlValue(request, "valueColNewAxis"); + + if (valueColId.length() > 0) { + DataColumnType dct = rdef.getColumnById(valueColId); + dct.setChartSeq(idx++); + dct.setChartColor(valueColColor); + dct.setColOnChart(valueColAxis.equals("Y") ? "1" : "0"); + } // if + } // for + + return true; // reportUpdated; + } // processChart + + public boolean processAdhocSchedule(HttpServletRequest request, String action) + throws Exception { + ReportSchedule reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE); + reportSchedule.setScheduleUserID(AppUtils.getUserID(request)); + reportSchedule.setSchedEnabled( + nvl(AppUtils.getRequestValue(request, "schedEnabled"), "N")); + reportSchedule.setStartDate( + AppUtils.getRequestNvlValue(request, "schedStartDate")); + reportSchedule.setEndDate( + AppUtils.getRequestNvlValue(request, "schedEndDate")); + reportSchedule.setEndHour(AppUtils.getRequestNvlValue(request, "schedEndHour")); + reportSchedule.setEndMin(AppUtils.getRequestNvlValue(request, "schedEndMin")); + reportSchedule.setEndAMPM(AppUtils.getRequestNvlValue(request, "schedEndAMPM")); + //schedRunDate + reportSchedule.setRunDate( + AppUtils.getRequestNvlValue(request, "schedRunDate").length()>0?AppUtils.getRequestNvlValue(request, "schedRunDate"):AppUtils.getRequestNvlValue(request, "schedStartDate")); + reportSchedule.setRunHour(AppUtils.getRequestNvlValue(request, "schedHour")); + reportSchedule.setRunMin(AppUtils.getRequestNvlValue(request, "schedMin")); + reportSchedule.setRunAMPM(AppUtils.getRequestNvlValue(request, "schedAMPM")); + reportSchedule.setRecurrence( + AppUtils.getRequestNvlValue(request, "schedRecurrence")); + reportSchedule.setConditional( + nvl(AppUtils.getRequestValue(request, "conditional"), "N")); + reportSchedule.setConditionSQL( + AppUtils.getRequestNvlValue(request, "conditionSQL")); + reportSchedule.setNotify_type( + AppUtils.getRequestNvlValue(request, "notify_type")); + reportSchedule.setDownloadLimit( + AppUtils.getRequestNvlValue(request, "downloadLimit")); + reportSchedule.setFormFields( + AppUtils.getRequestNvlValue(request, "formFields")); + reportSchedule.setAttachmentMode( + AppUtils.getRequestNvlValue(request, "sendAttachment")); + + String userId = AppUtils.getRequestNvlValue(request, "schedEmailAdd"); + String roleId = AppUtils.getRequestNvlValue(request, "schedEmailAddRole"); + int flag = 0; + if ((!(userId.length()>0 || roleId.length()>0) && (reportSchedule.getEmailToUsers().isEmpty() && reportSchedule.getEmailToRoles().isEmpty())) ) { + flag = 1; + } + + if (flag == 1 || (action.equals(AppConstants.WA_ADD_USER) || action.equals(AppConstants.WA_ADD_ROLE)) ) { + String loggedInUserId = AppUtils.getUserID(request); + if (Globals.getUseLoginIdInSchedYN().equals("Y")){ + reportSchedule.addEmailToUser(loggedInUserId, AppUtils.getUserLoginId(request)); + } else + reportSchedule.addEmailToUser(loggedInUserId, (AppUtils.getUserName(loggedInUserId).length()>0?AppUtils.getUserName(loggedInUserId):(AppUtils.getUserLoginId(loggedInUserId).length()>0?AppUtils.getUserLoginId(loggedInUserId):loggedInUserId) )); + } + if (action.equals(AppConstants.WA_ADD_USER)) { + //String userId = AppUtils.getRequestNvlValue(request, "schedEmailAdd"); + String userName = AppUtils.getUserName(userId); + if (Globals.getUseLoginIdInSchedYN().equals("Y")){ + String userLoginId = AppUtils.getUserLoginId(userId); + if (userId.length() > 0 && (userLoginId != null && userLoginId.length() > 0)) + reportSchedule.addEmailToUser(userId, userLoginId); + else { + if (userId.length() > 0 && (userName != null && userName.length() > 0) ) + reportSchedule.addEmailToUser(userId, userName); + else { + reportSchedule.addEmailToUser(userId, userId); + } + } + }else{ + if (userId.length() > 0 && (userName != null && userName.length() > 0) ) + reportSchedule.addEmailToUser(userId, userName); + else { + reportSchedule.addEmailToUser(userId, userId); + } + } + + } else if (action.equals(AppConstants.WA_DELETE_USER)) + reportSchedule.removeEmailToUser( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + else if (action.equals(AppConstants.WA_ADD_ROLE)) { + //String roleId = AppUtils.getRequestNvlValue(request, "schedEmailAddRole"); + String roleName = AppUtils.getRoleName(roleId); + if (roleId.length() > 0 && roleName != null) + reportSchedule.addEmailToRole(roleId, roleName); + } else if (action.equals(AppConstants.WA_DELETE_ROLE)) + reportSchedule.removeEmailToRole( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule); + return true; + } // processAdhocSchedule + + private boolean processSchedule(HttpServletRequest request, String action) + throws Exception { + // Added for form field chaining in schedule tab so that setParamValues() is called + request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y"); + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + ReportSchedule reportSchedule = rdef.getReportSchedule(); + reportSchedule.setScheduleUserID(AppUtils.getUserID(request)); + reportSchedule.setSchedEnabled( + nvl(AppUtils.getRequestValue(request, "schedEnabled"), "N")); + reportSchedule.setStartDate( + AppUtils.getRequestNvlValue(request, "schedStartDate")); + reportSchedule.setEndDate( + AppUtils.getRequestNvlValue(request, "schedEndDate")); + reportSchedule.setEndHour(AppUtils.getRequestNvlValue(request, "schedEndHour")); + reportSchedule.setEndMin(AppUtils.getRequestNvlValue(request, "schedEndMin")); + reportSchedule.setEndAMPM(AppUtils.getRequestNvlValue(request, "schedEndAMPM")); + //schedRunDate + reportSchedule.setRunDate( + AppUtils.getRequestNvlValue(request, "schedRunDate").length()>0?AppUtils.getRequestNvlValue(request, "schedRunDate"):AppUtils.getRequestNvlValue(request, "schedStartDate")); + reportSchedule.setRunHour(AppUtils.getRequestNvlValue(request, "schedHour")); + reportSchedule.setRunMin(AppUtils.getRequestNvlValue(request, "schedMin")); + reportSchedule.setRunAMPM(AppUtils.getRequestNvlValue(request, "schedAMPM")); + reportSchedule.setRecurrence( + AppUtils.getRequestNvlValue(request, "schedRecurrence")); + reportSchedule.setConditional( + nvl(AppUtils.getRequestValue(request, "conditional"), "N")); + reportSchedule.setConditionSQL( + AppUtils.getRequestNvlValue(request, "conditionSQL")); + reportSchedule.setNotify_type( + AppUtils.getRequestNvlValue(request, "notify_type")); + reportSchedule.setDownloadLimit( + AppUtils.getRequestNvlValue(request, "downloadLimit")); + reportSchedule.setFormFields( + AppUtils.getRequestNvlValue(request, "formFields")); + reportSchedule.setAttachmentMode( + AppUtils.getRequestNvlValue(request, "sendAttachment")); + + reportSchedule.setEncryptMode( + AppUtils.getRequestNvlValue(request, "encryptMode")); + if (action.equals(AppConstants.WA_ADD_USER)) { + String userId = AppUtils.getRequestNvlValue(request, "schedEmailAdd"); + String userName = AppUtils.getUserName(userId); + if (Globals.getUseLoginIdInSchedYN().equals("Y")){ + String userLoginId = AppUtils.getUserLoginId(userId); + if (userId.length() > 0 && (userLoginId != null && userLoginId.length() > 0)) + reportSchedule.addEmailToUser(userId, userLoginId); + else { + if (userId.length() > 0 && (userName != null && userName.length() > 0) ) + reportSchedule.addEmailToUser(userId, userName); + else { + reportSchedule.addEmailToUser(userId, userId); + } + } + }else{ + if (userId.length() > 0 && (userName != null && userName.length() > 0) ) + reportSchedule.addEmailToUser(userId, userName); + else { + reportSchedule.addEmailToUser(userId, userId); + } + } + } else if (action.equals(AppConstants.WA_DELETE_USER)) + reportSchedule.removeEmailToUser( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + else if (action.equals(AppConstants.WA_ADD_ROLE)) { + String roleId = AppUtils.getRequestNvlValue(request, "schedEmailAddRole"); + String roleName = AppUtils.getRoleName(roleId); + if (roleId.length() > 0 && roleName != null) + reportSchedule.addEmailToRole(roleId, roleName); + } else if (action.equals(AppConstants.WA_DELETE_ROLE)) + reportSchedule.removeEmailToRole( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + + return true; + } // processSchedule + + private boolean processUserAccess(HttpServletRequest request, String action) + throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String ownerID = AppUtils.getRequestNvlValue(request, "reportOwner"); + String rPublic = nvl(AppUtils.getRequestValue(request, "public"), "N"); + + boolean reportUpdated = (!(ownerID.equals(nvl(rdef.getOwnerID())) && rPublic + .equals(rdef.isPublic() ? "Y" : "N"))); + + rdef.getReportSecurity().setOwnerID(ownerID); + rdef.setPublic(rPublic.equals("Y")); + + if (action.equals(AppConstants.WA_ADD_USER)) + rdef.getReportSecurity().addUserAccess( + AppUtils.getRequestNvlValue(request, "newUserId"), "Y"); + else if (action.equals(AppConstants.WA_DELETE_USER)) + rdef.getReportSecurity().removeUserAccess( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + else if (action.equals(AppConstants.WA_GRANT_USER)) + rdef.getReportSecurity().updateUserAccess( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID), "N"); + else if (action.equals(AppConstants.WA_REVOKE_USER)) + rdef.getReportSecurity().updateUserAccess( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID), "Y"); + else if (action.equals(AppConstants.WA_ADD_ROLE)) + rdef.getReportSecurity().addRoleAccess( + AppUtils.getRequestNvlValue(request, "newRoleId"), "Y"); + else if (action.equals(AppConstants.WA_DELETE_ROLE)) + rdef.getReportSecurity().removeRoleAccess( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID)); + else if (action.equals(AppConstants.WA_GRANT_ROLE)) + rdef.getReportSecurity().updateRoleAccess( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID), "N"); + else if (action.equals(AppConstants.WA_REVOKE_ROLE)) + rdef.getReportSecurity().updateRoleAccess( + AppUtils.getRequestNvlValue(request, AppConstants.RI_DETAIL_ID), "Y"); + + return reportUpdated; + } // processUserAccess + + private boolean processClearLog(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + String user_id = AppUtils.getUserID(request); + // Modified so that only the logged in user entries are erased. - Sundar + ReportLoader.clearReportLogEntries(rdef.getReportID(), user_id); + return false; + } // processClearLog + + private boolean processValidateSQL(HttpServletRequest request) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + String sql = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "reportSQL")); + request.setAttribute("sqlValidated", "N"); + rdef.parseReportSQL(sql); + request.setAttribute("sqlValidated", "Y"); + + return true; + } // processValidateSQL + + + /*****For Report Maps - Start******/ + private boolean processMap(HttpServletRequest request, String action) throws Exception { + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + + org.openecomp.portalsdk.analytics.xmlobj.ReportMap repMap = rdef.getReportMap(); + //clearing already added + if (repMap != null){ + repMap.getMarkers().removeAll(repMap.getMarkers()); + } + String addressColumn = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "addressColumn0")); + System.out.println(" #$%#$%#$% -- address col = " + addressColumn); + String dataColumn = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "dataColumn0")); + String legendColumn = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "legendColumn")); + //String legendDisplayName = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "dataHeaderL")); + //if(nvl(legendDisplayName).length()<=0) legendDisplayName = legendColumn; + String color = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "markerColor0")); + String isMapAllowed = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "isMapAllowed")); + String useDefaultSize = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "useDefaultSize")); + String height = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "height")); + String width = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "width")); + System.out.println(" #$%#$%#$% -- useDefaultSize="+ useDefaultSize+" height = " + height+" width="+width); + + String addAddress = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "addAddress")); + String latCol = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "latColumn")); + String longCol = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "longColumn")); + String colorCol = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "colorColumn")); + if (isMapAllowed.equals("")) + isMapAllowed = "N"; + if (useDefaultSize.equals("")) + useDefaultSize = "N"; + if (repMap == null) + rdef.setReportMap(new ObjectFactory().createReportMap()); + repMap.setAddressColumn(addressColumn); + repMap.setDataColumn(dataColumn); + repMap.setIsMapAllowedYN(isMapAllowed); + repMap.setUseDefaultSize(useDefaultSize); + repMap.setMarkerColor(color); + repMap.setAddAddressInDataYN(addAddress); + repMap.setLatColumn(latCol); + repMap.setLongColumn(longCol); + repMap.setColorColumn(colorCol); + repMap.setHeight(height.trim()); + repMap.setWidth(width.trim()); + repMap.setLegendColumn(legendColumn); + //repMap.setLegendDisplayName(legendDisplayName); + + Marker m = new ObjectFactory().createMarker(); + m.setAddressColumn(addressColumn); + m.setDataColumn(dataColumn); + repMap.getMarkers().add(m); + String markerCountString = AppUtils.getRequestNvlValue(request, "markerCount"); + int markerCount = 0; + if (markerCountString != null && markerCountString.equals("") == false){ + markerCount = new Integer(markerCountString).intValue(); + } + for (int i = 1; i < markerCount; i ++){ + String additionalAddressColumn = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "addressColumn" + i)); + String additionalDataHeader = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "dataHeader" + i)); + String additionalData = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "dataColumn" + i)); + String additionalColor = XSSFilter.filterRequestOnlyScript(AppUtils.getRequestNvlValue(request, "markerColor" + i)); + if (additionalAddressColumn.equals("1") == false){ + m = new ObjectFactory().createMarker(); + m.setAddressColumn(additionalAddressColumn); + m.setDataHeader(additionalDataHeader); + m.setDataColumn(additionalData); + m.setMarkerColor(additionalColor); + repMap.getMarkers().add(m); + } + } + return true; + } // processMap + /*****For Report Maps - End******/ + + +} // WizardProcessor diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequence.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequence.java new file mode 100644 index 00000000..81308909 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequence.java @@ -0,0 +1,191 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.model.base.*; +import org.openecomp.portalsdk.analytics.model.definition.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequence extends Vector { + // private String currentStep = AppConstants.WS_DEFINITION; + private int currentStepIdx = 0; + + private String currentSubStep = ""; + + private int nextElemIdx = 0; + + public void resetNext() { + resetNext(0); + } // resetNext + + public void resetNext(int toPos) { + nextElemIdx = toPos; + } // resetNext + + public boolean hasNext() { + return (nextElemIdx < size()); + } // hasNext + + public String getNext() { + return hasNext() ? getStep(nextElemIdx++) : null; + } // getNext + + // ***************************************************** + + public WizardSequence() { + add(AppConstants.WS_DEFINITION); + } // WizardSequence + + private String getStep(int index) { + return (String) get(index); + } // getStep + + private int getStepIndex(String step) { + for (int i = 0; i < size(); i++) + if (getStep(i).equals(step)) + return i; + + throw new IndexOutOfBoundsException(); + } // getStepIndex + + /* + * private String getInitialStep() { return getStep(0); } // getInitialStep + * + * private String getFinalStep() { return getStep(getStepCount()-1); } // + * getFinalStep + */ + private boolean isInitialStep(int index) { + return (index == 0); + } // isInitialStep + + /* + * private boolean isInitialStep(String step) { return + * isInitialStep(getStepIndex(step)); } // isInitialStep + */ + private boolean isFinalStep(int index) { + if (index == 0) + return false; + + return (index == (getStepCount() - 1)); + } // isFinalStep + + /* + * private boolean isFinalStep(String step) { return + * isFinalStep(getStepIndex(step)); } // isFinalStep + */ + + private int getNextStepIndex(int index) { + return (index == (getStepCount() - 1)) ? index : (index + 1); + } // getNextStep + + /* + * private String getNextStep(String step) { return + * getStep(getNextStepIndex(getStepIndex(step))); } // getNextStep + * + * private String getNextStep(String step, String subStep) { + * if(subStep.length()>0) return step; + * + * return getNextStep(step); } // getNextStep + */ + private int getPrevStepIndex(int index) { + return (index == 0) ? index : (index - 1); + } // getPrevStepIndex + + /* + * private String getPrevStep(String step) { return + * getStep(getPrevStepIndex(getStepIndex(step))); } // getPrevStep + * + * private String getPrevStep(String step, String subStep) { + * if(subStep.length()>0) return step; + * + * return getPrevStep(step); } // getPrevStep + */ + // ***************************************************** + public int getStepCount() { + return size(); + } // getStepCount + + public int getCurrentStepIndex() { + return currentStepIdx + 1; + } // getCurrentStepIndex + + public String getCurrentStep() { + return getStep(currentStepIdx); + } // getCurrentStep + + public String getCurrentSubStep() { + return currentSubStep; + } // getCurrentSubStep + + public boolean isInitialStep() { + return isInitialStep(currentStepIdx); + } // isInitialStep + + public boolean isFinalStep() { + return isFinalStep(currentStepIdx); + } // isFinalStep + + public void performAction(String action, ReportDefinition rdef) { + if (action.equals(AppConstants.WA_BACK)) + if (currentSubStep.length() > 0) + currentSubStep = ""; + else + currentStepIdx = getPrevStepIndex(currentStepIdx); + else if (action.equals(AppConstants.WA_NEXT)) { + if (currentSubStep.length() > 0) + currentSubStep = ""; + else { + currentStepIdx = getNextStepIndex(currentStepIdx); + if (rdef != null) + if (!rdef.getReportDefType().equals(AppConstants.RD_SQL_BASED)) + if (getCurrentStep().equals(AppConstants.WS_TABLES) + && (rdef.getDataSourceList().getDataSource().size() == 0)) + currentSubStep = AppConstants.WSS_ADD; + else if (getCurrentStep().equals(AppConstants.WS_COLUMNS) + && (rdef.getAllColumns().size() == 0)) + currentSubStep = (rdef.getReportType().equals( + AppConstants.RT_CROSSTAB) ? AppConstants.WSS_ADD + : AppConstants.WSS_ADD_MULTI); + } + } else if (action.equals(AppConstants.WA_EDIT) || action.equals(AppConstants.WA_ADD) + || action.equals(AppConstants.WA_ADD_MULTI) + || action.equals(AppConstants.WA_ORDER_ALL)|| action.equals(AppConstants.WSS_ADD_BLANK) || action.equals(AppConstants.WA_MODIFY)) { + currentSubStep = action; + } + else if (currentSubStep.equals(AppConstants.WSS_ADD) + || currentSubStep.equals(AppConstants.WSS_EDIT)) + currentSubStep = AppConstants.WSS_EDIT; + else + currentSubStep = ""; + } // performAction + + public void performGoToStep(String step) { + int stepIdx = getStepIndex(step); + + if (stepIdx >= 0 && stepIdx < getStepCount()) { + currentStepIdx = stepIdx; + currentSubStep = ""; + } + } // performGoToStep + +} // WizardSequence diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceCrossTab.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceCrossTab.java new file mode 100644 index 00000000..686c8b7b --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceCrossTab.java @@ -0,0 +1,45 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceCrossTab extends WizardSequence { + + public WizardSequenceCrossTab(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_TABLES); + add(AppConstants.WS_COLUMNS); + add(AppConstants.WS_FORM_FIELDS); + add(AppConstants.WS_FILTERS); + add(AppConstants.WS_JAVASCRIPT); + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceCrossTab + +} // WizardSequenceCrossTab diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceDashboard.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceDashboard.java new file mode 100644 index 00000000..d8424f2c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceDashboard.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceDashboard extends WizardSequence { + + public WizardSequenceDashboard(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceDashboard + +} // WizardSequenceDashboard diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceLinear.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceLinear.java new file mode 100644 index 00000000..2015a7b9 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceLinear.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceLinear extends WizardSequence { + + public WizardSequenceLinear(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_TABLES); + add(AppConstants.WS_COLUMNS); + add(AppConstants.WS_FORM_FIELDS); + add(AppConstants.WS_FILTERS); + add(AppConstants.WS_SORTING); + //add(AppConstants.WS_JAVASCRIPT); + //add(AppConstants.WS_CHART); + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceLinear + +} // WizardSequenceLinear diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedCrossTab.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedCrossTab.java new file mode 100644 index 00000000..db2f8c6f --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedCrossTab.java @@ -0,0 +1,44 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceSQLBasedCrossTab extends WizardSequence { + + public WizardSequenceSQLBasedCrossTab(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_SQL); + add(AppConstants.WS_COLUMNS); + add(AppConstants.WS_FORM_FIELDS); + add(AppConstants.WS_JAVASCRIPT); + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceSQLBasedCrossTab + +} // WizardSequenceSQLBasedCrossTab diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedHive.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedHive.java new file mode 100644 index 00000000..7f64cb9a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedHive.java @@ -0,0 +1,46 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceSQLBasedHive extends WizardSequence { + + public WizardSequenceSQLBasedHive(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_SQL); + add(AppConstants.WS_COLUMNS); + add(AppConstants.WS_FORM_FIELDS); + add(AppConstants.WS_JAVASCRIPT); + add(AppConstants.WS_CHART); + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_MAP); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceSQLBasedHive + +} // WizardSequenceSQLBasedHive diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinear.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinear.java new file mode 100644 index 00000000..a19c66b4 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinear.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceSQLBasedLinear extends WizardSequence { + + public WizardSequenceSQLBasedLinear(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_SQL); + add(AppConstants.WS_COLUMNS); + add(AppConstants.WS_FORM_FIELDS); + //add(AppConstants.WS_JAVASCRIPT); + //if(!Globals.showAnimatedChartOnly()) + //add(AppConstants.WS_CHART); + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_MAP); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceSQLBasedLinear + +} // WizardSequenceSQLBasedLinear diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinearDatamining.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinearDatamining.java new file mode 100644 index 00000000..5c8759d9 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/controller/WizardSequenceSQLBasedLinearDatamining.java @@ -0,0 +1,46 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.controller; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class WizardSequenceSQLBasedLinearDatamining extends WizardSequence { + + public WizardSequenceSQLBasedLinearDatamining(boolean userIsAuthorizedToSeeLog) { + super(); + + add(AppConstants.WS_SQL); + add(AppConstants.WS_COLUMNS); + add(AppConstants.WS_FORM_FIELDS); + add(AppConstants.WS_DATA_FORECASTING); + add(AppConstants.WS_JAVASCRIPT); + add(AppConstants.WS_CHART); + add(AppConstants.WS_USER_ACCESS); + //add(AppConstants.WS_SCHEDULE); + if (userIsAuthorizedToSeeLog) + if (Globals.getEnableReportLog()) + add(AppConstants.WS_REPORT_LOG); + add(AppConstants.WS_RUN); + } // WizardSequenceSQLBasedLinear + +} // WizardSequenceSQLBasedLinear diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorException.java new file mode 100644 index 00000000..f0de41f8 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorException.java @@ -0,0 +1,35 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +public class RaptorException extends Exception { + + public RaptorException(String message) { + super(message); + } + + public RaptorException(String message, Throwable ex) { + super(message, ex); + } + + public RaptorException(Throwable ex) { + super(ex); + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorRuntimeException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorRuntimeException.java new file mode 100644 index 00000000..98938f49 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorRuntimeException.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +public class RaptorRuntimeException extends RaptorException { + + public RaptorRuntimeException (String message) { + super(message); + } + + public RaptorRuntimeException (String message, Throwable ex) { + super(message, ex); + } + + public RaptorRuntimeException (Throwable ex) { + super(ex); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorSchedularException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorSchedularException.java new file mode 100644 index 00000000..3339ba5f --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/RaptorSchedularException.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +public class RaptorSchedularException extends RaptorException { + + public RaptorSchedularException (String message) { + super(message); + } + + public RaptorSchedularException (String message, Throwable ex) { + super(message, ex); + } + + public RaptorSchedularException (Throwable ex) { + super(ex); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ReportSQLException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ReportSQLException.java new file mode 100644 index 00000000..f78810ee --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ReportSQLException.java @@ -0,0 +1,51 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +public class ReportSQLException extends RaptorException { + private String reportSQL = null; + + public ReportSQLException(String message, String reportSQL) { + super(message); + + this.reportSQL = reportSQL; + } // ReportSQLException + + public ReportSQLException(String message, String reportSQL, Throwable ex) { + super(message, ex); + + this.reportSQL = reportSQL; + } // ReportSQLException + + public ReportSQLException(String message) { + super(message); + this.reportSQL = ""; + } // ReportSQLException + + public ReportSQLException(String message, Throwable ex) { + super(message, ex); + this.reportSQL = ""; + } // ReportSQLException + + public String getReportSQL() { + return reportSQL; + } // getReportSQL + +} // ReportSQLException diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserAccessException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserAccessException.java new file mode 100644 index 00000000..ed88f5ff --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserAccessException.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +public class UserAccessException extends RaptorRuntimeException { + + public UserAccessException(Throwable ex) { + super(ex); + } // UserAccessException + + public UserAccessException(String reportID, String userName, String accessType) { + //super("User " + userName + " does NOT have " + accessType + " permission for report " + // + reportID); + super("Access denied. Please contact Administrator"); + } // UserAccessException + +} // UserAccessException diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserDefinedException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserDefinedException.java new file mode 100644 index 00000000..0145ecfd --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/UserDefinedException.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +/** + * @author sundar + * This class is exclusively used to print error messages to user. + * + */ +public class UserDefinedException extends RaptorRuntimeException { + + public UserDefinedException(String message) { + super(message); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ValidationException.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ValidationException.java new file mode 100644 index 00000000..ee26abd0 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/error/ValidationException.java @@ -0,0 +1,42 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.error; + +public class ValidationException extends RaptorRuntimeException { + private String fieldID = null; + + public ValidationException(String message) { + super(message); + } + + public ValidationException(String message, Throwable ex) { + super(message, ex); + } + + public ValidationException(String fieldID, String message) { + super(message); + this.fieldID = fieldID; + } + + public String getFieldID() { + return fieldID; + } + +} // ValidationException diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/Line.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/Line.java new file mode 100644 index 00000000..00445606 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/Line.java @@ -0,0 +1,86 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.line; + +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import org.openecomp.portalsdk.analytics.gmap.map.NovaMap; + +public class Line { + private NovaMap map; + private LineCollection lineCollection; + private ArrayList selectionList; + private Set lineIDSet; + + public Line(NovaMap map) { + this.map = map; + lineCollection = new LineCollection(); + lineIDSet = new HashSet(); + selectionList = new ArrayList(); + } + + public ArrayList lineExist(Point2D screenPoint) { + ArrayList existLineInfo = null; + String selectedLine = null; + String selectedType = null; + int nearest = -1; + int nodeSize = map.getShapeWidth(); + nodeSize = nodeSize > 20 ? 20 : nodeSize; + int x0 = (int) screenPoint.getX(); + int y0 = (int) screenPoint.getY(); + + ArrayList lineInfos = lineCollection.getLineCollection(); + + for (LineInfo lineInfo : lineInfos) { + Point2D point1 = map.getScreenPointFromLonLat(lineInfo.geoCoordinate1.longitude, lineInfo.geoCoordinate1.latitude); + Point2D point2 = map.getScreenPointFromLonLat(lineInfo.geoCoordinate2.longitude, lineInfo.geoCoordinate2.latitude); + int x1 = (int) point1.getX(); + int y1 = (int) point1.getY(); + int x2 = (int) point2.getX(); + int y2 = (int) point2.getY(); + int diff = Math.abs((x0 - x1) * (y0 - y2) - (x0 - x2) * (y0 - y1)); + + if (((x1 - x0) * (x2 - x0) <= (nodeSize * 2)) && ((y1 - y0) * (y2 - y0) <= (nodeSize * 2)) && + diff < (Math.abs(y1 - y2) + Math.abs(x1 - x2)) * (int) (nodeSize * .2)) { + if (nearest == -1) { + nearest = diff; + selectedLine = lineInfo.getLineID(); + selectedType = lineInfo.getLineType(); + } + else if (diff <= nearest) { + nearest = diff; + selectedLine = lineInfo.getLineID(); + selectedType = lineInfo.getLineType(); + } + + if (existLineInfo == null) { + existLineInfo = new ArrayList(); + } + + existLineInfo.add(lineInfo); + } + } + + return existLineInfo; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineCollection.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineCollection.java new file mode 100644 index 00000000..249b277c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineCollection.java @@ -0,0 +1,158 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.line; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +public class LineCollection { + private Set selectedLine; // all selected node + private String lineID; // last clicked node + private ArrayList lineCollection; + + public LineCollection() { + lineCollection = new ArrayList(20000); + selectedLine = new HashSet(); + } + + public void addSelectedLine(String lineID) { + selectedLine.add(lineID); + } + + public void removeSelectedLine(String lineID) { + selectedLine.remove(lineID); + } + + public Set getSelectedLine() { + return selectedLine; + } + + public boolean containSelectedLine(String lineID) { + return selectedLine.contains(lineID); + } + + public void clearSelectedLine() { + selectedLine.clear(); + } + + public void addLine(LineInfo lineInfo) { + lineCollection.add(lineInfo); + } + + public ArrayList getLineCollection() { + return lineCollection; + } + + public LineInfo getLine(String lineID) { + for (LineInfo lineInfo : lineCollection) { + if (lineInfo.getLineID().equalsIgnoreCase(lineID)) { + return lineInfo; + } + } + + return null; + } + + public LineInfo getLine(String lineID, String lineType) { + for (LineInfo lineInfo : lineCollection) { + if (lineInfo.getLineID().equalsIgnoreCase(lineID) && lineInfo.getLineType().equalsIgnoreCase(lineType)) { + return lineInfo; + } + } + + return null; + } + + public LineInfo getLine(String nodeID1, String nodeID2, boolean dummy) { + for (LineInfo lineInfo : lineCollection) { + if ((lineInfo.getNodeID1().equalsIgnoreCase(nodeID1) && lineInfo.getNodeID2().equalsIgnoreCase(nodeID2)) || + (lineInfo.getNodeID1().equalsIgnoreCase(nodeID2) && lineInfo.getNodeID2().equalsIgnoreCase(nodeID1))) { + return lineInfo; + } + } + + return null; + } + + public LineInfo removeLine(String lineID) { + for (int i = 0; i < lineCollection.size(); i++) { + if (lineCollection.get(i).getLineID().equalsIgnoreCase(lineID)) { + return lineCollection.remove(i); + } + } + + removeSelectedLine(lineID); + return null; + } + + public LineInfo removeLine(String lineID, String lineType) { + for (int i = 0; i < lineCollection.size(); i++) { + if (lineCollection.get(i).getLineID().equalsIgnoreCase(lineID) && + lineCollection.get(i).getLineType().equalsIgnoreCase(lineType)) { + return lineCollection.remove(i); + } + } + + removeSelectedLine(lineID); + return null; + } + + public void clearLine() { + lineCollection.clear(); + selectedLine.clear(); + } + + public int getSize() { + return lineCollection.size(); + } + + public String getLineID() { + return lineID; + } + + public void setLineID(String lineID) { + this.lineID = lineID; + } + + public void clearAllCollection () { + clearLine(); + clearSelectedLine(); + this.lineID = null; + } + + public String[] getWildCardLine(String lineID) { + ArrayList list = new ArrayList(); + + for (LineInfo lineInfo : lineCollection) { + if (lineInfo.getLineID().toLowerCase().indexOf(lineID.toLowerCase()) != -1) { + list.add(lineInfo.getLineID()); + } + } + + String[] result = new String[list.size()]; + + for (int i = 0; i < list.size(); i++) { + result[i] = list.get(i); + } + + return result; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineInfo.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineInfo.java new file mode 100644 index 00000000..fd9ec94c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/line/LineInfo.java @@ -0,0 +1,190 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.line; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openecomp.portalsdk.analytics.gmap.map.GeoCoordinate; + +public class LineInfo { + public GeoCoordinate geoCoordinate1; + public GeoCoordinate geoCoordinate2; + + private String nodeID1; + private String nodeID2; + + private String lineID; + private String lineType; + private String lineDescription; + + private boolean moveable; + private boolean deleteable; + + private int state; + + private Map lineAttributes; + + public LineInfo(String nodeID1, String nodeID2) { + this.nodeID1 = nodeID1; + this.nodeID2 = nodeID2; + lineAttributes = new HashMap(); + } + + public LineInfo clone() { + LineInfo lineInfo = new LineInfo(nodeID1, nodeID2); + lineInfo.geoCoordinate1.longitude = geoCoordinate1.longitude; + lineInfo.geoCoordinate1.latitude = geoCoordinate1.latitude; + lineInfo.geoCoordinate2.longitude = geoCoordinate2.longitude; + lineInfo.geoCoordinate2.latitude = geoCoordinate2.latitude; + lineInfo.setDescription(lineDescription); + lineInfo.setLineID(lineID); + lineInfo.setLineType(lineType); + lineInfo.setMoveable(moveable); + lineInfo.setDeleteable(deleteable); + lineInfo.setState(state); + lineInfo.initializeAttributes(lineAttributes); + + return lineInfo; + } + + public void setLineID(String lineID) { + this.lineID = lineID; + geoCoordinate1 = new GeoCoordinate(); + geoCoordinate2 = new GeoCoordinate(); + } + + public String getLineID() { + return lineID; + } + + public void setLineType(String lineType) { + this.lineType = lineType; + } + + public String getLineType() { + return lineType; + } + + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + + public String getDescription() { + return lineDescription; + } + + public void setDescription(String lineDescription) { + this.lineDescription = lineDescription; + } + + public boolean isMoveable() { + return moveable; + } + + public void setMoveable(boolean moveable) { + this.moveable = moveable; + } + + public String getNodeID1() { + return nodeID1; + } + + public void setNodeID1(String nodeID1) { + this.nodeID1 = nodeID1; + } + + public String getNodeID2() { + return nodeID2; + } + + public void setNodeID2(String nodeID2) { + this.nodeID2 = nodeID2; + } + + public void initializeAttributes(Map lineAttributes) { + this.lineAttributes.clear(); + Set keySet = lineAttributes.keySet(); + Iterator iter = keySet.iterator(); + + while (iter.hasNext()) { + String key = iter.next(); + this.lineAttributes.put(key, lineAttributes.get(key)); + } + } + + public void setAttribute(String key, String value) { + lineAttributes.put(key, value); + } + + public String getAttribute(String key) { + String value = lineAttributes.get(key); + return value; + } + + public List getAttributeKeys() { + Set keySet = lineAttributes.keySet(); + List keys = new ArrayList(keySet.size()); + Iterator iter = keySet.iterator(); + + while (iter.hasNext()) { + String key = iter.next(); + + if (key.indexOf("x_") != 0) { + keys.add(key); + } + } + + return keys; + } + + public List getAttributeInternalKeys() { + Set keySet = lineAttributes.keySet(); + List internalKeys = new ArrayList(); + Iterator iter = keySet.iterator(); + + while (iter.hasNext()) { + String key = iter.next(); + + if (key.indexOf("x_") == 0) { + key = key.substring(2); + internalKeys.add(key); + } + } + + return internalKeys; + } + + public boolean isDeleteable() { + return deleteable; + } + + public void setDeleteable(boolean deleteable) { + this.deleteable = deleteable; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/ColorProperties.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/ColorProperties.java new file mode 100644 index 00000000..a87af423 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/ColorProperties.java @@ -0,0 +1,119 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.map; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class ColorProperties { + private NovaMap map; + + private Map colorProperties; + private ArrayList nodeLegends; + private ArrayList lineLegends; + + public ColorProperties(NovaMap map) { + this.map = map; + colorProperties = new HashMap(); + } + + public void setColor(String type, String color) { + //colorProperties.put(type + "_COLOR", color); + String[] rgb = color.split(","); + colorProperties.put(type + "_COLOR", + new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), + Integer.parseInt(rgb[2]))); + } + +// public void setColor(String type, int number, String color) { +// Object object = colorProperties.get(type + ":" + number + "_COLOR"); +// +// if (object != null) { +// Color oldColor = (Color) object; +// +// if (!color.equals(oldColor.getRed() + "," + oldColor.getGreen() + "," + oldColor.getBlue())) { +// String[] rgb = color.split(","); +// colorProperties.put(type + ":" + number + "_COLOR", +// new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), +// Integer.parseInt(rgb[2]))); +// } +// } +// else { +// String[] rgb = color.split(","); +// colorProperties.put(type + ":" + number + "_COLOR", +// new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), +// Integer.parseInt(rgb[2]))); +// } +// } + +// public Color getColor(String type, int number) { +// return (Color) colorProperties.get(type + ":" + number + "_COLOR"); +// } + + public Color getColor(String type) { + return (Color) colorProperties.get(type + "_COLOR"); + } + + public void setShape(String type, String shape) { + colorProperties.put(type + "_SHAPE", shape); + } + + public void setShape(String type, int number, String shape) { + colorProperties.put(type + ":" + number + "_SHAPE", shape); + } + + public String getShape(String type) { + return (String) colorProperties.get(type + "_SHAPE"); + } + + public String getShape(String type, int number) { + return (String) colorProperties.get(type + ":" + number + "_SHAPE"); + } + + public void setSize(String type, String size) { + colorProperties.put(type + "_SIZE", size); + } + + public void setSize(String type, int number, String size) { + colorProperties.put(type + ":" + number + "_SIZE", size); + } + + public int getSize(String type) { + Object object = colorProperties.get(type + "_SIZE"); + + if (object == null) { + return 0; + } + + return Integer.parseInt(object.toString()); + } + + public int getSize(String type, int number) { + Object object = colorProperties.get(type + ":" + number + "_SIZE"); + + if (object == null) { + return 0; + } + + return Integer.parseInt(object.toString()); + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GMapProperties.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GMapProperties.java new file mode 100644 index 00000000..036e83bf --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GMapProperties.java @@ -0,0 +1,49 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.map; + +import java.io.InputStream; +import java.util.Properties; + +import org.openecomp.portalsdk.analytics.system.Globals; + +public class GMapProperties { + + public static String getProjectFolder() { + return Globals.getProjectFolder(); + } + + public static String getMarketShapefileFolder() { + return Globals.getMarketShapefileFolder(); + } + + public static String getTileSize() { + return Globals.getTileSize(); + } + + public static String getOutputFolder() { + return Globals.getOutputFolder(); + } + + public static String getTempFolderURL() { + return Globals.getTempFolderURL(); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GeoCoordinate.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GeoCoordinate.java new file mode 100644 index 00000000..ed3fe8bd --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/GeoCoordinate.java @@ -0,0 +1,25 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.map; + +public class GeoCoordinate { + public double longitude; + public double latitude; +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/MapConstant.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/MapConstant.java new file mode 100644 index 00000000..cef1f4ad --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/MapConstant.java @@ -0,0 +1,44 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.map; + +public class MapConstant { + public static final String CURSOR = "CURSOR"; + public static final String FILLED_TRIANGLE = "FILLED TRIANGLE"; + public static final String FILLED_SQUARE = "FILLED SQUARE"; + public static final String FILLED_CIRCLE = "FILLED CIRCLE"; + public static final String FILLED_DIAMOND = "FILLED DIAMOND"; + public static final String HOLLOW_TRIANGLE = "HOLLOW TRIANGLE"; + public static final String HOLLOW_SQUARE = "HOLLOW SQUARE"; + public static final String HOLLOW_CIRCLE = "HOLLOW CIRCLE"; + public static final String HOLLOW_DIAMOND = "HOLLOW DIAMOND"; + + public static int NORMAL_STATE = 1; + public static int FORCE_STATE = 2; + public static int EXCLUDE_STATE = 3; + public static int ANY_STATE = 4; + + public static int ZOOM_MIN = 1; + public static int ZOOM_MAX = 22; + + public static final double ARROW_ANGLE_HIGH = .75; + public static final double ARROW_ANGLE_LOW = .45; + public static final double ZOOMING_INDEX = .6; +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/NovaMap.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/NovaMap.java new file mode 100644 index 00000000..ba245064 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/NovaMap.java @@ -0,0 +1,504 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.map; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.geom.AffineTransform; +import java.awt.geom.NoninvertibleTransformException; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.HashSet; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.analytics.gmap.line.Line; +import org.openecomp.portalsdk.analytics.gmap.line.LineInfo; +import org.openecomp.portalsdk.analytics.gmap.map.layer.SwingLayer; +import org.openecomp.portalsdk.analytics.gmap.node.Node; +import org.openecomp.portalsdk.analytics.gmap.node.NodeInfo; + +public class NovaMap { + private static int[] shapeWidth; + + public static final Font TEXT_FONT = new Font("sans-serif", Font.BOLD, 12); + public static final Font HEADER_FONT = new Font("sans-serif", Font.ITALIC+Font.BOLD, 12); + + private HashSet showList; + private ArrayList swingLayers; + private AffineTransform transform; + + private Node node; + private Line line; + private ColorProperties colorProperties; + + private Rectangle2D defaultBoundary; + + private int zoomLevel; + + private String currentYearMonth; + + private String dataLoaded = ""; + + /** + * size in screen pixel + */ + private Rectangle boundingBox; + + /** + * size in pixel web mercator projection + */ + private Rectangle2D mapArea; + + /** + * size in longitude latitude + */ + private Rectangle2D geoArea; + + public static double[] meter2pixel; + + private boolean showLegend = false; + + static { + initShapeWidth(); + initMeter2Pixel(); + } + + private static void initMeter2Pixel() { + meter2pixel = new double[MapConstant.ZOOM_MAX - MapConstant.ZOOM_MIN+1]; + meter2pixel[0] = 156543.04/2; + for(int i=1; i 4 && i < 10) { + width += 2; + } + else { + width++; + } + + shapeWidth[i] = width; + } + } + + public NovaMap() { + boundingBox = new Rectangle(); + mapArea = new Rectangle2D.Double(); + geoArea = new Rectangle2D.Double(); + showList = new HashSet(); + swingLayers = new ArrayList(); + } + + + + public int getBestZoomLevel(double Latitude1, double Longitude1, + double Latitude2, double Longitude2, + double height, double width) { + + if (height==0) + height=700; + if (width==0) + width=1200; + + double lat1 = Math.min(Latitude1, Latitude1); + double CosLat = Math.cos(Math.toRadians(lat1)); + double Wmeter = getDistance( + lat1, Longitude1, + lat1, Longitude2)/CosLat; + double Hmeter = getDistance( + Latitude1, Longitude1, + Latitude2, Longitude1)/CosLat; + + int zoom = 0; + if(Latitude1 == Latitude2 && Longitude1 == Longitude2) + zoom = 15; + if (zoom <= 0) { + for(; + zoom < meter2pixel.length + && (width*meter2pixel[zoom]) > Wmeter + && (height*meter2pixel[zoom]) > Hmeter; + ++zoom) ; + } + +// && (1200*meter2pixel[zoom]) > Wmeter +// && (700*meter2pixel[zoom]) > Hmeter; + + return zoom + MapConstant.ZOOM_MIN-1; + } + + public static double getDistance(double Latitude1, double Longitude1, + double Latitude2, double Longitude2) { + Latitude1 = Math.toRadians(Latitude1); + Longitude1 = Math.toRadians(Longitude1); + Latitude2 = Math.toRadians(Latitude2); + Longitude2 = Math.toRadians(Longitude2); + + final double R = 6371.0; // earth's mean radius in km + double dSinLat05 = Math.sin( (Latitude2 - Latitude1)/2 ); + double dSinLong05 = Math.sin( (Longitude2 - Longitude1)/2 ); + double a = dSinLat05 * dSinLat05 + + Math.cos(Latitude1) * Math.cos(Latitude2) * dSinLong05 * dSinLong05; + double c = (0==a || 1==a) + ? 0 + : 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0-a)); + return R * c * 1000.0; //in meters + } + + public Rectangle getBoundingBox() { + return boundingBox; + } + + public void setBoundingBox(int width, int height) { + boundingBox.setSize(width, height); + } + + public void setNode(Node node) { + this.node = node; + } + + public Node getNode() { + return node; + } + + public void setLine(Line line) { + this.line = line; + } + + public Line getLine() { + return line; + } + + public void setColorProperties(ColorProperties colorProperties) { + this.colorProperties = colorProperties; + } + + public ColorProperties getColorProperties() { + return colorProperties; + } + + public void setZoomLevel(int zoomLevel) { + this.zoomLevel = zoomLevel; + } + + public int getZoomLevel() { + return zoomLevel; + } + + public void addShowList(String type) { + showList.add(type.toUpperCase()); + } + + public void addShowList(String type, int number) { + showList.add(type.toUpperCase() + ":" + number); + } + + public void removeShowList(String type) { + showList.remove(type.toUpperCase()); + } + + public void removeShowList(String type, int number) { + showList.remove(type.toUpperCase() + ":" + number); + } + + public void clearShowList() { + showList.clear(); + } + + public HashSet getShowList() { + return showList; + } + + public boolean containsShowList(String type) { + return showList.contains(type.toUpperCase()); + } + + public boolean containsShowList(String type, int number) { + return showList.contains(type.toUpperCase() + ":" + number); + } + + public int getShowListSize() { + return showList.size(); + } + + public void addSwingLayer(SwingLayer swingLayer) { + swingLayers.add(swingLayer); + } + + public void removeSwingLayer(SwingLayer swingLayer) { + swingLayers.remove(swingLayer); + } + + public void clearSwingLayers() { + swingLayers.clear(); + } + + public ArrayList getSwingLayers() { + return swingLayers; + } + + public int getShapeWidth() { + return shapeWidth[getZoomLevel()>=22?21:(getZoomLevel()<=8 ? 8:getZoomLevel())]; + } + + public Point2D getPixelPos(double latitude, double longitude) { + double sinLatitude = Math.sin(Math.toRadians(latitude)); + return new Point2D.Double( + ((longitude + 180.0) / 360.0) * 256.0 * (1< existNodeInfo = node.nodeExist(screenPoint); + + if (existNodeInfo == null) { + ArrayList existLineInfo = line.lineExist(screenPoint); + + if (existLineInfo == null) { + + } + else { + System.out.println("%%%%%%map.singleLeftClick end 1"); + return existLineInfo; + } + } + else { +// if (existNodeInfo.size() == 1) { +// NodeInfo nodeInfo = existNodeInfo.get(0); +// node.getNodeCollection().clearSelectedNode(); +// node.getNodeCollection().addSelectedNode(nodeInfo.getID(), nodeInfo.getLegendID()); +// return getSelectedImage(geoArea); +// } +// else { +// return existNodeInfo; +// } + + System.out.println("%%%%%%map.singleLeftClick end 2"); + return existNodeInfo; + } + + System.out.println("%%%%%%map.singleLeftClick end 3"); + return null; + } + + public String getCurrentYearMonth() { + return currentYearMonth; + } + + public void setCurrentYearMonth(String currentYearMonth) { + this.currentYearMonth = currentYearMonth; + } + + public Rectangle2D getDefaultBoundary() { + return defaultBoundary; + } + + public void setDefaultBoundary(Rectangle2D defaultBoundary) { + this.defaultBoundary = defaultBoundary; + } + + public boolean isShowLegend() { + return showLegend; + } + + public void setShowLegend(boolean showLegend) { + this.showLegend = showLegend; + } + + public String getDataLoaded() { + return dataLoaded; + } + + public void setDataLoaded(String dataLoaded) { + this.dataLoaded = dataLoaded; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/layer/SwingLayer.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/layer/SwingLayer.java new file mode 100644 index 00000000..9100637c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/map/layer/SwingLayer.java @@ -0,0 +1,235 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.map.layer; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Stroke; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.analytics.gmap.map.ColorProperties; +import org.openecomp.portalsdk.analytics.gmap.map.MapConstant; +import org.openecomp.portalsdk.analytics.gmap.map.NovaMap; +import org.openecomp.portalsdk.analytics.gmap.node.Node; +import org.openecomp.portalsdk.analytics.gmap.node.NodeInfo; +import org.openecomp.portalsdk.analytics.system.Globals; + + +public class SwingLayer { + private Rectangle shape; + private NovaMap map; + + public SwingLayer(NovaMap map) { + this.map = map; + } + + public boolean paintLayer(HttpServletRequest request, Graphics2D g2d, Rectangle bounds, Rectangle2D mapArea, Graphics2D g2Legend) { + return paintNodes(request, g2d, bounds, mapArea, g2Legend); + } + + protected boolean paintNodes(HttpServletRequest request, Graphics2D g2d, Rectangle bounds, Rectangle2D mapArea, Graphics2D g2Legend) { + boolean painted = false; + Node node = map.getNode(); + ColorProperties colorProperties = map.getColorProperties(); + int legendSize = 0; + if(map.isShowLegend()) + legendSize = map.getShowListSize(); + Object showListArr[] = ((HashSet)map.getShowList()).toArray(); + HashMap hashMap = node.getNodeCollection().getNodeCollection(); + Set set = hashMap.entrySet(); + int width = map.getShapeWidth(); + ArrayList visibleLabel = new ArrayList(151); + Color oldColor = g2d.getColor(); + Stroke oldStroke = g2d.getStroke(); + int textWidth = 0; + int legendLength = 0; + for (int i = 0; i < showListArr.length; i++) { + legendLength = ((String)showListArr[i]).length(); + if(legendLength > textWidth) textWidth = legendLength; + } + Point2D point = null; + for (Iterator iterator = set.iterator(); iterator.hasNext();) { + Map.Entry entry = (Map.Entry) iterator.next(); + NodeInfo nodeInfo = (NodeInfo) entry.getValue(); + + String id1 = (String) request.getAttribute("server_process_id"); + String id2 = (String) request.getSession().getAttribute("server_process_id"); + + if (!id1.equals(id2)) { + request.setAttribute("server_process_interrupted", true); + System.out.println("swing layer interrupted"); + return false; + } + //System.out.println("%%%%%%%getImage. no of T1%%%%%%" + nodeInfo.getAttribute("x_sequence")); + + + point = map.getPixelPos(nodeInfo.geoCoordinate.latitude, nodeInfo.geoCoordinate.longitude); + + if (!mapArea.contains(point.getX(), point.getY())) { + continue; + } + + painted = true; + + g2d.setColor(colorProperties.getColor(nodeInfo.getNodeType())); + + Point2D xyPoint = map.getScreenPointFromPixel(point.getX(), point.getY()); + int width2 = (colorProperties.getSize(nodeInfo.getNodeType()) * width) / 5; + + if (shape == null) { + shape = new Rectangle((int) xyPoint.getX(), (int) xyPoint.getY(), width2, width2); + } + else { + shape.setRect((int) xyPoint.getX(), (int) xyPoint.getY(), width2, width2); + } + + if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.FILLED_SQUARE)) { + g2d.fillRect((int) shape.getCenterX() - width2, (int) shape.getCenterY() - width2, width2, width2); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.HOLLOW_SQUARE)) { + g2d.drawRect((int) shape.getCenterX() - width2, (int) shape.getCenterY() - width2, width2, width2); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.FILLED_CIRCLE)) { + g2d.fillOval((int) shape.getCenterX() - width2, (int) shape.getCenterY() - width2, width2, width2); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.HOLLOW_CIRCLE)) { + g2d.drawOval((int) shape.getCenterX() - width2, (int) shape.getCenterY() - width2, width2, width2); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.FILLED_TRIANGLE)) { + int[] xPoints = {(int) shape.getX(), (int) shape.getX() - width2 / 2, (int) shape.getX() + width2 / 2}; + int[] yPoints = {(int) shape.getY() + width2 / 2, (int) shape.getY() - width2 / 2, (int) shape.getY() - width2 / 2}; + g2d.fillPolygon(xPoints, yPoints, xPoints.length); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.HOLLOW_TRIANGLE)) { + int[] xPoints = {(int) shape.getX(), (int) shape.getX() - width2 / 2, (int) shape.getX() + width2 / 2}; + int[] yPoints = {(int) shape.getY() + width2 / 2, (int) shape.getY() - width2 / 2, (int) shape.getY() - width2 / 2}; + g2d.drawPolygon(xPoints, yPoints, xPoints.length); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.FILLED_DIAMOND)) { + int[] xPoints = {(int) shape.getX() - width2 / 2, (int) shape.getX(), (int) shape.getX() + width2 / 2, (int) shape.getX()}; + int[] yPoints = {(int) shape.getY() , (int) shape.getY() - width2 / 2, (int) shape.getY(), (int) shape.getY() + width2 / 2}; + g2d.fillPolygon(xPoints, yPoints, xPoints.length); + } + else if (colorProperties.getShape(nodeInfo.getNodeType())!=null && colorProperties.getShape(nodeInfo.getNodeType()).equalsIgnoreCase(MapConstant.HOLLOW_DIAMOND)) { + int[] xPoints = {(int) shape.getX() - width2 / 2, (int) shape.getX(), (int) shape.getX() + width2 / 2, (int) shape.getX()}; + int[] yPoints = {(int) shape.getY() , (int) shape.getY() - width2 / 2, (int) shape.getY(), (int) shape.getY() + width2 / 2}; + g2d.drawPolygon(xPoints, yPoints, xPoints.length); + } else { + g2d.drawRect((int) shape.getCenterX() - width2, (int) shape.getCenterY() - width2, width2, width2); + } + + if (nodeInfo.isMoveable()) { + int fontSize = width / 2; + fontSize = fontSize > 14 ? 14 : fontSize; + fontSize = (colorProperties.getSize(nodeInfo.getNodeType()) * fontSize) / 5; + Font font = new Font("sans-serif", Font.BOLD, fontSize); + g2d.setFont(font); + g2d.setColor(Color.BLACK); + g2d.drawString("M", shape.x + width2 / 2, shape.y); + } + +// if (map.containsShowLabelList(nodeInfo.getNodeType())) { +// g2d.setColor(Color.BLACK); +// FontMetrics metrics = g2d.getFontMetrics(); +// int x = shape.x - metrics.stringWidth(nodeInfo.getID()) / 2; +// int y = shape.y + width2 * 4 / 3; +// g2d.drawString(nodeInfo.getID(), x, y); +// } + } + String legendName = ""; + int baseY = 0; + baseY = (int)(20*showListArr.length) + 20;//+5; + int baseX = 0; + if(map.isShowLegend()) { + for (int i = showListArr.length-1; i>=0; i--) { + + legendName = (String)showListArr[i]; + //for(int i = 0; i < showListArr.length; i++ ) { + if(i == showListArr.length-1){ + textWidth = (textWidth<="Legend".length())?"Legend".length():textWidth; + g2Legend.setColor(Color.WHITE); + //g2d.draw(new Rectangle2D.Double((int) bounds.getMaxX()*0.1, (int) bounds.getMaxY()*0.75*showListArr.length, (int) bounds.getMaxX()*0.75, (int) bounds.getMaxY()*0.75)); + g2Legend.fill3DRect((int)(0), (int)(0), (int) bounds.getWidth() , (int)(baseY) , true); // (int)(bounds.getMaxX()*0.9)- (int)(bounds.getMaxX()*0.25) + //if(i == 0){ + g2Legend.setColor(Color.BLACK); + g2Legend.setFont(NovaMap.HEADER_FONT); + g2Legend.drawString("Legend", (int) (10), 10); + } + int[] xPointsL = {(int) (10 - width / 2), (int) (10), (int) (10 + width/2), (int) (10)}; + int[] yPointsL = {(int) (15*i+5+20), (int) (15*i+5+20 - width / 2), (int) (15*i+5+20), (int) (15*i+5+20 + width / 2)}; + g2Legend.setColor(colorProperties.getColor( ((String)showListArr[i]).toUpperCase())); + g2Legend.fillPolygon(xPointsL, yPointsL, xPointsL.length); + g2Legend.setFont(NovaMap.TEXT_FONT); + g2Legend.setColor(Color.BLACK); + + g2Legend.drawString(legendName.substring(0, legendName.indexOf("-")), (int) (10) + width+10, (int) (15*i)+10+20); + } + } + +/* g2d.drawString("0", (int) bounds.getMaxX()/2+20 + width+10, 0); + g2d.drawString("50", (int) bounds.getMaxX()/2+20 + width+10, 50); + g2d.drawString("100", (int) bounds.getMaxX()/2+20 + width+10, 100); + g2d.drawString("200", (int) bounds.getMaxX()/2+20 + width+10, 200); + g2d.drawString("400", (int) bounds.getMaxX()/2+20 + width+10, 400); + g2d.drawString("600", (int) bounds.getMaxX()/2+20 + width+10, 600); +*/ +// g2d.setFont(NovaMap.TEXT_FONT); +// g2d.setColor(Color.BLACK); + if(nvl(map.getDataLoaded()).trim().length() > 0) { + g2d.setColor(Color.WHITE); + g2d.fill3DRect(new Double(bounds.getMinX()).intValue(), new Double(bounds.getMaxY()).intValue()-30, (int) bounds.getWidth() , (int)(30) , true); // (int)(bounds.getMaxX()*0.9)- (int)(bounds.getMaxX()*0.25) + g2d.setColor(Color.RED); + g2d.setFont(NovaMap.HEADER_FONT); + g2d.drawString(Globals.getUserDefinedMessageForMemoryLimitReached() + " "+ map.getDataLoaded()+ " were downloaded to Map.", new Double(bounds.getMinX()).intValue()+80, new Double(bounds.getMaxY()).intValue()-15); + } + + //g2d.drawString("Hello", new Double(bounds.getMinX()).intValue()+20, new Double(bounds.getMaxY()).intValue()-50); + FontMetrics metrics = g2d.getFontMetrics(); + + for (int i = 0; i < visibleLabel.size(); i++) { + String[] properties = visibleLabel.get(i).split(">>>"); + int x = Integer.parseInt(properties[1]) - metrics.stringWidth(properties[0]) / 2; + int y = Integer.parseInt(properties[2]) + Integer.parseInt(properties[3]) * 4 / 3; + g2d.drawString(properties[0], x, y); + } + + g2d.setColor(oldColor); + g2d.setStroke(oldStroke); + + return painted; + } + + private String nvl(String s) { + return (s == null) ? "" : s; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/Node.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/Node.java new file mode 100644 index 00000000..a58eb458 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/Node.java @@ -0,0 +1,178 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.node; + +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.openecomp.portalsdk.analytics.gmap.map.MapConstant; +import org.openecomp.portalsdk.analytics.gmap.map.NovaMap; + +public class Node { + private Set nodeIDSet; + private NodeCollection nodeCollection; + private ArrayList selectionList; + private NovaMap map; + + public Node(NovaMap map) { + this.map = map; + nodeCollection = new NodeCollection(); + nodeIDSet = new HashSet(); + selectionList = new ArrayList(); + } + + public NodeInfo addNode(double longitude, double latitude, String nodeType, String nodeID, + String nodeAttributes, int state, boolean moveable, boolean deleteable) { + NodeInfo nodeInfo = new NodeInfo(nodeID); + nodeInfo.geoCoordinate.longitude = longitude; + nodeInfo.geoCoordinate.latitude = latitude; + nodeInfo.setNodeType(nodeType); + nodeInfo.setState(state); + nodeInfo.setMoveable(moveable); + nodeInfo.setDeleteable(deleteable); + nodeInfo.initializeAttributes(nodeAttributes); + + //if (nodeCollection.getNode(nodeInfo.getNodeID()+""+nodeInfo.getNodeType()) == null) { + nodeCollection.addNode(nodeInfo); + nodeIDSet.add(nodeID); +/* } + else { + return nodeCollection.getNode(nodeType); + } +*/ + return nodeInfo; + } + + /** + * + */ +/* public void updateNumberT1(String currentYearMonth) { + ArrayList nodeCollection = this.nodeCollection.getNodeCollection(); + + for (NodeInfo nodeInfo : nodeCollection) { + nodeInfo.setAttribute(NodeInfo.NUMBER_OF_T1_KEY, nodeInfo.getAttribute(currentYearMonth)); + } + } +*/ +/* public Set getUniqueNumberT1(String currentYearMonth) { + ArrayList nodeCollection = this.nodeCollection.getNodeCollection(); + Set numberT1Set = new TreeSet(); + + for (NodeInfo nodeInfo : nodeCollection) { + numberT1Set.add(Integer.parseInt(nodeInfo.getAttribute(currentYearMonth).toString())); + } + + return numberT1Set; + } +*/ + public void updateNumberT1(String currentYearMonth) { + HashMap hashMap = this.nodeCollection.getNodeCollection(); + Set set = hashMap.entrySet(); + + for (Iterator iterator = set.iterator(); iterator.hasNext();) { + Map.Entry entry = (Map.Entry) iterator.next(); + NodeInfo nodeInfo = (NodeInfo) entry.getValue(); + nodeInfo.setAttribute(NodeInfo.NUMBER_OF_T1_KEY, nodeInfo.getAttribute(currentYearMonth)); + } + + } + + public Set getUniqueNumberT1(String currentYearMonth) { + HashMap hashMap = this.nodeCollection.getNodeCollection(); + Set set = hashMap.entrySet(); + Set numberT1Set = new TreeSet(); + + for (Iterator iterator = set.iterator(); iterator.hasNext();) { + Map.Entry entry = (Map.Entry) iterator.next(); + NodeInfo nodeInfo = (NodeInfo) entry.getValue(); + numberT1Set.add(Integer.parseInt(nodeInfo.getAttribute(currentYearMonth).toString())); + } + + return numberT1Set; + } + + /** + * + * @param screenPoint + * @return list of NodeInfo within screenPoint. If not found, null is return + */ + public ArrayList nodeExist(Point2D screenPoint) { + ArrayList existNodeInfo = null; + int nearest = 9999; + String selectedNode = null; + String selectedType = null; + int nodeSize = map.getShapeWidth(); + HashMap hashMap = nodeCollection.getNodeCollection(); + Set set = hashMap.entrySet(); + //ArrayList list = nodeCollection.getNodeCollection(); + + for (Iterator iterator = set.iterator(); iterator.hasNext();) { + Map.Entry entry = (Map.Entry) iterator.next(); + NodeInfo nodeInfo = (NodeInfo) entry.getValue(); + + if (!map.containsShowList(nodeInfo.getNodeType())) { + continue; + } + + int width = (map.getColorProperties().getSize(nodeInfo.getNodeType()) * nodeSize) / 5; + int foundFactor = (int) (MapConstant.ZOOMING_INDEX * width); + Point2D nodePoint = map.getScreenPointFromLonLat(nodeInfo.geoCoordinate.longitude, + nodeInfo.geoCoordinate.latitude); + + int lonDiff = (int) Math.abs(screenPoint.getX() - nodePoint.getX()); + int latDiff = (int) Math.abs(screenPoint.getY() - nodePoint.getY()); + + if (lonDiff < foundFactor && latDiff < foundFactor) { + if (lonDiff < nearest) { + nearest = lonDiff; + selectedNode = nodeInfo.getNodeID(); + selectedType = nodeInfo.getNodeType(); + nodeCollection.setNodeID(selectedNode); + } + + if (existNodeInfo == null) { + existNodeInfo = new ArrayList(); + } + + existNodeInfo.add(nodeInfo); + } + } + + return existNodeInfo; + } + + public NodeCollection getNodeCollection() { + return nodeCollection; + } + + public void clearNodeIDSet() { + nodeIDSet.clear(); + } + + public void clearSelectionList() { + selectionList.clear(); + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeCollection.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeCollection.java new file mode 100644 index 00000000..35801a4d --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeCollection.java @@ -0,0 +1,188 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.node; + + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +public class NodeCollection { + private Set selectedNode; // all selected node + private String nodeID; // last clicked node + private HashMap nodeCollection; + + public NodeCollection() { + selectedNode = new HashSet(); + nodeCollection = new HashMap(20000); + } + + public void addSelectedNode(String nodeID) { + selectedNode.add(nodeID); + } + + public void removeSelectedNode(String nodeID) { + selectedNode.remove(nodeID); + } + + public boolean containSelectedNode(String nodeID) { + return selectedNode.contains(nodeID); + } + + public void addSelectedNode(String nodeID, String nodeType) { + selectedNode.add(nodeID + ">>" + nodeType); + } + + public void removeSelectedNode(String nodeID, String nodeType) { + selectedNode.remove(nodeID + ">>" + nodeType); + } + + public void clearSelectedNode() { + selectedNode.clear(); + } + + public boolean containSelectedNode(String nodeID, String nodeType) { + return selectedNode.contains(nodeID + ">>" + nodeType); + } + + public Set getSelectedNode() { + return selectedNode; + } + + public void addNode(NodeInfo nodeInfo) { + if (nodeInfo == null) { + System.out.println("nodeInfo is null"); + } + nodeCollection.put(nodeInfo.getNodeID()+""+nodeInfo.getNodeType(), nodeInfo); + } + + public HashMap getNodeCollection() { + return nodeCollection; + } + +/* public NodeInfo getNode(String nodeID) { + for (NodeInfo nodeInfo : nodeCollection) { + if (nodeInfo.getNodeID().equalsIgnoreCase(nodeID) ) { + return nodeInfo; + } + } + + return null; + } +*/ +/* public NodeInfo getNode(String nodeID, String nodeType) { + for (NodeInfo nodeInfo : nodeCollection) { + if (nodeInfo.getNodeID().equalsIgnoreCase(nodeID) && nodeInfo.getNodeType().equalsIgnoreCase(nodeType)) { + return nodeInfo; + } + } + + return null; + } +*/ + public NodeInfo getNode(String nodeType) { + return (NodeInfo)nodeCollection.get(nodeType); + } +/* public ArrayList getWildCardNode(String nodeID, String nodeType) { + ArrayList list = new ArrayList(); + + for (NodeInfo nodeInfo : nodeCollection) { + if (nodeInfo.getNodeType().equalsIgnoreCase(nodeType) && + nodeInfo.getNodeID().toLowerCase().indexOf(nodeID.toLowerCase()) != -1) { + list.add(nodeInfo); + } + } + + return list; + }*/ + +/* public NodeInfo removeNode(String nodeID) { + for (int i = 0; i < nodeCollection.size(); i++) { + if (nodeCollection.get(i).getNodeID().equalsIgnoreCase(nodeID)) { + return nodeCollection.remove(i); + } + } + + removeSelectedNode(nodeID); + return null; + } + + public NodeInfo removeNode(String nodeID, String nodeType) { + for (int i = 0; i < nodeCollection.size(); i++) { + if (nodeCollection.get(i).getNodeID().equalsIgnoreCase(nodeID) && + nodeCollection.get(i).getNodeType().equalsIgnoreCase(nodeType)) { + return nodeCollection.remove(i); + } + } + + removeSelectedNode(nodeID, nodeType); + return null; + } +*/ +/* public void removeNode(String nodeType) { + nodeCollection.remove(nodeType); + }*/ + +/* public ArrayList getCellsiteLocation(String location, boolean exactMatch) { + ArrayList list = new ArrayList(); + + for (NodeInfo nodeInfo : nodeCollection) { + if (nodeInfo.getAttribute("Location") == null) { + continue; + } + + if (exactMatch) { + if (nodeInfo.getAttribute("Location").equalsIgnoreCase(location)) { + list.add(nodeInfo); + } + } + else { + if (nodeInfo.getAttribute("Location").toUpperCase().indexOf(location.toUpperCase()) != -1) { + list.add(nodeInfo); + } + } + } + + return list; + } +*/ + public void clearNode() { + nodeCollection.clear(); + selectedNode.clear(); + } + + public int getSize() { + return nodeCollection.size(); + } + + public void setNodeID(String nodeID) { + this.nodeID = nodeID; + } + + public String getNodeID() { + return nodeID; + } + + public void clearAllCollection() { + this.clearNode(); + this.clearSelectedNode(); + this.nodeID = ""; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeInfo.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeInfo.java new file mode 100644 index 00000000..d1676e02 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/node/NodeInfo.java @@ -0,0 +1,210 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.node; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TreeMap; + +import org.openecomp.portalsdk.analytics.gmap.map.GeoCoordinate; + +public class NodeInfo { + public static final String NUMBER_OF_T1_KEY = "x_numberOfT1"; + public static final String SEQUENCE_KEY = "x_sequence"; + + public GeoCoordinate geoCoordinate; + + private String nodeID; + private String nodeType; + private int state; + private boolean moveable; + private boolean deleteable; + + private List lineIDS; + private Map nodeAttributes; + + public NodeInfo(String nodeID) { + this.nodeID = nodeID; + lineIDS = new ArrayList(); + nodeAttributes = new TreeMap(); + geoCoordinate = new GeoCoordinate(); + } + + public NodeInfo clone() { + NodeInfo nodeInfo = new NodeInfo(nodeID); + nodeInfo.geoCoordinate.longitude = geoCoordinate.longitude; + nodeInfo.geoCoordinate.latitude = geoCoordinate.latitude; + nodeInfo.setMoveable(moveable); + nodeInfo.setNodeType(nodeType); + nodeInfo.setNodeID(nodeID); + nodeInfo.setState(state); + nodeInfo.setLineIDS(cloneLineIDS()); + nodeInfo.setDeleteable(deleteable); + nodeInfo.initializeAttributes(nodeAttributes); + + return nodeInfo; + } + + public void addLineID(String lineID, String lineType) { + if (!lineIDS.contains(lineID + ">>" + lineType)) { + lineIDS.add(lineID + ">>" + lineType); + } + } + + public void removeLineID(String lineID, String lineType) { + lineIDS.remove(lineID + ">>" + lineType); + } + + public String getLineID(String lineID, String lineType) { + for (Object temp : lineIDS) { + if (temp.toString().equals(lineID + ">>" + lineType)) { + return temp.toString(); + } + } + + return null; + } + + public List getLineIDS() { + return lineIDS; + } + + public void printLineIDS() { + Iterator iter = lineIDS.iterator(); + + while (iter.hasNext()) { + System.out.println(iter.next()); + } + } + + public List cloneLineIDS() { + List lineIDS = new ArrayList(); + + for (String lineID : this.lineIDS) { + lineIDS.add(lineID); + } + + return lineIDS; + } + + public void setLineIDS(List lineIDS) { + this.lineIDS = lineIDS; + } + + public void setNodeID(String nodeID) { + this.nodeID = nodeID; + } + + public String getNodeID() { + return nodeID; + } + + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + public String getNodeType() { + return nodeType; + } + + public void setState(int state) { + this.state = state; + } + + public int getState() { + return state; + } + + public void setMoveable(boolean moveable) { + this.moveable = moveable; + } + + public boolean isMoveable() { + return moveable; + } + + public void setDeleteable(boolean deleteable) { + this.deleteable = deleteable; + } + + public boolean isDeleteable() { + return deleteable; + } + + public String getAttribute(String key) { + String value = nodeAttributes.get(key); + return value; + } + + public void initializeAttributes(Map nodeAttributes) { + this.nodeAttributes.clear(); + Set keySet = nodeAttributes.keySet(); + Iterator iter = keySet.iterator(); + + while (iter.hasNext()) { + String key = iter.next(); + this.nodeAttributes.put(key, nodeAttributes.get(key)); + } + } + + public void initializeAttributes(String nodeAttributes) { + if (nodeAttributes == null) { + return; + } + + this.nodeAttributes.clear(); + StringTokenizer tokenizer = new StringTokenizer(nodeAttributes, "|"); + + while (tokenizer.hasMoreTokens()) { + String attribute = tokenizer.nextToken(); + StringTokenizer attributeTokenizer = new StringTokenizer(attribute, "="); + + if (attributeTokenizer.countTokens() == 2) { + String key = attributeTokenizer.nextToken(); + String value = attributeTokenizer.nextToken(); + this.nodeAttributes.put(key, value); + } + } + } + + public void setAttribute(String key, String value) { + nodeAttributes.put(key, value); + } + + public List getAttributeKeys() { + Set keySet = nodeAttributes.keySet(); + List keys = new ArrayList(keySet.size()); + Iterator iter = keySet.iterator(); + + while (iter.hasNext()) { + String key = iter.next(); + + if (key.indexOf("x_") != 0) { + keys.add(key); + } + } + + return keys; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/MapUtils.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/MapUtils.java new file mode 100644 index 00000000..b281c230 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/MapUtils.java @@ -0,0 +1,70 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.utils; + +import java.io.ObjectOutputStream; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + + + +public class MapUtils { + public static final short PLATE_CARREE_PROJECTION = 0; + public static final short WEB_MERCATOR_PROJECTION = 1; + + + + private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new java.text.SimpleDateFormat("yyyy/MM"); + + + + public static String getModifiedMarketID(String marketID) { + String modifiedMarketID = marketID.replaceAll("/", "_"); + modifiedMarketID = modifiedMarketID.replaceAll(" ", "_"); + return modifiedMarketID; + } + + /** + * increment or decrement + * @param currentYearMonth + * @param value - positive value will increment, otherwise decrement + * @return null if not valid number (must be between 2008/01 to 2010/12) + */ + + +/* public static void saveColor(HttpServletRequest request, DomainService domainService, + String type, String colorValue) { +// String userID = Integer.toString(UserUtils.getUserId(request)); +// MapColorPK colorPK = new MapColorPK(); +// MapColorVO colorVO = new MapColorVO(); +// +// colorPK.setUserID(userID); +// colorPK.setPrefID(type); +// colorVO.setMapColorPK(colorPK); +// colorVO.setColorValue(colorValue); +// +// domainService.saveDomainObject(colorVO); + } */ +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/SwingWorker.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/SwingWorker.java new file mode 100644 index 00000000..26cbb114 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/gmap/utils/SwingWorker.java @@ -0,0 +1,155 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.gmap.utils; + +import javax.swing.SwingUtilities; + +/** + * This is the 3rd version of SwingWorker (also known as + * SwingWorker 3), an abstract class that you subclass to + * perform GUI-related work in a dedicated thread. For + * instructions on using this class, see: + * + * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html + * + * Note that the API changed slightly in the 3rd version: + * You must now invoke start() on the SwingWorker after + * creating it. + */ +public abstract class SwingWorker { + private Object value; // see getValue(), setValue() + private Thread thread; + + /** + * Class to maintain reference to current worker thread + * under separate synchronization control. + */ + private static class ThreadVar { + private Thread thread; + ThreadVar(Thread t) { thread = t; } + synchronized Thread get() { return thread; } + synchronized void clear() { thread = null; } + } + + private ThreadVar threadVar; + + /** + * Get the value produced by the worker thread, or null if it + * hasn't been constructed yet. + */ + protected synchronized Object getValue() { + return value; + } + + /** + * Set the value produced by worker thread + */ + private synchronized void setValue(Object x) { + value = x; + } + + /** + * Compute the value to be returned by the get method. + */ + public abstract Object construct(); + + /** + * Called on the event dispatching thread (not on the worker thread) + * after the construct method has returned. + */ + public void finished() { + } + + /** + * A new method that interrupts the worker thread. Call this method + * to force the worker to stop what it's doing. + */ + public void interrupt() { + Thread t = threadVar.get(); + if (t != null) { + t.interrupt(); + } + threadVar.clear(); + } + + /** + * Return the value created by the construct method. + * Returns null if either the constructing thread or the current + * thread was interrupted before a value was produced. + * + * @return the value created by the construct method + */ + public Object get() { + while (true) { + Thread t = threadVar.get(); + if (t == null) { + return getValue(); + } + try { + t.join(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); // propagate + return null; + } + } + } + + + /** + * Start a thread that will call the construct method + * and then exit. + */ + public SwingWorker() { + final Runnable doFinished = new Runnable() { + public void run() { finished(); } + }; + + Runnable doConstruct = new Runnable() { + public void run() { + try { + setValue(construct()); + } + finally { + threadVar.clear(); + } + + SwingUtilities.invokeLater(doFinished); + } + }; + + Thread t = new Thread(doConstruct); + threadVar = new ThreadVar(t); + } + + /** + * Start the worker thread. + */ + public void start() { + Thread t = threadVar.get(); + if (t != null) { + t.start(); + } + } + + public Thread getThread() { + return threadVar.get(); + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/DataCache.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/DataCache.java new file mode 100644 index 00000000..2757c595 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/DataCache.java @@ -0,0 +1,516 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model; + +import java.util.*; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.ReportSQLException; +import org.openecomp.portalsdk.analytics.model.base.*; +import org.openecomp.portalsdk.analytics.model.definition.*; +import org.openecomp.portalsdk.analytics.model.runtime.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class DataCache extends org.openecomp.portalsdk.analytics.RaptorObject { + private static Vector dataViewActions = null; + + private static Vector publicReportIdNames = null; + + private static Vector privateReportIdNames = null; + + private static Vector groupReportIdNames = null; + + private static Vector reportTableSources = null; + + private static Vector reportTableJoins = null; + + private static HashMap reportTableDbColumns = new HashMap(); + + private static HashMap reportFieldDbLookups = null; + + public DataCache() { + } + + public static Vector getDataViewActions() throws RaptorException { + if (dataViewActions == null) + /* try */{ + dataViewActions = new Vector(); + + //DataSet ds = DbUtils + // .executeQuery("SELECT ts.web_view_action FROM cr_table_source ts WHERE ts.web_view_action IS NOT NULL"); + + String sql = Globals.getTheDataViewActions(); + DataSet ds = DbUtils + .executeQuery(sql); + + for (int i = 0; i < ds.getRowCount(); i++) + dataViewActions.add(ds.getString(i, 0)); + } // catch(Exception e) {} + + return dataViewActions; + } // getDataViewActions + + public static Vector getPublicReportIdNames() throws RaptorException { + // if(publicReportIdNames==null) => needs to be up-to-date at any time + /* try */{ + publicReportIdNames = new Vector(); + + //DataSet ds = DbUtils + // .executeQuery("SELECT rep_id, title FROM cr_report WHERE public_yn = 'Y' ORDER BY title"); + + String sql = Globals.getThePublicReportIdNames(); + DataSet ds = DbUtils + .executeQuery(sql); + for (int i = 0; i < ds.getRowCount(); i++) + publicReportIdNames + .add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1))); + } // catch(Exception e) {} + + return publicReportIdNames; + } // getPublicReportIdNames + + public static Vector getPrivateAccessibleReportIdNames(String user_id, Vector userRoles) throws RaptorException { + // if(publicReportIdNames==null) => needs to be up-to-date at any time + /* try */{ + privateReportIdNames = new Vector(); + + // StringBuffer query = new StringBuffer(" SELECT cr.rep_id, cr.title FROM cr_report cr "); + String sql = Globals.getThePrivateAccessibleNamesA(); + //query.append(" WHERE cr.rep_id not in (select rep_id from cr_report_access cra where user_id = '"+ user_id+"' "); + sql = sql.replace("[user_id]", user_id); + StringBuffer query = new StringBuffer(sql); + for (int i = 0; i < userRoles.size(); i++) { + if( i == 0){ + // query.append(" OR role_id in ("); + query.append(Globals.getThePrivateAccessibleNamesIf()); + } + if(i < (userRoles.size()-1)) + query.append((String)userRoles.get(i) + ","); + + else if(i == (userRoles.size()-1)) + query.append((String)userRoles.get(i)+")"); + + } + //query.append(" ) "); + //query.append(" AND public_yn = 'N' and cr.owner_id = '"+ user_id+"' order by 2 "); + sql = Globals.getThePrivateAccessibleNamesB(); + sql = sql.replace("[user_id]", user_id); + query.append(sql); + + DataSet ds = DbUtils + .executeQuery(query.toString() ); + + for (int i = 0; i < ds.getRowCount(); i++) + privateReportIdNames + .add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1))); + } // catch(Exception e) {} + + return privateReportIdNames; + } // getPrivateAccessibleReportIdNames + + + public static Vector getGroupAccessibleReportIdNames(String user_id, Vector userRoles) throws RaptorException { + // if(publicReportIdNames==null) => needs to be up-to-date at any time + /* try */{ + groupReportIdNames = new Vector(); + + //StringBuffer query = new StringBuffer(" SELECT cr.rep_id, cr.title FROM cr_report cr "); + //query.append(" WHERE cr.rep_id in (select rep_id from cr_report_access cra where user_id = '"+ user_id+"' "); + String sql = Globals.getTheGroupAccessibleNamesA(); + sql = sql.replace("[user_id]", user_id); + StringBuffer query = new StringBuffer(sql); + + for (int i = 0; i < userRoles.size(); i++) { + if( i == 0) + query.append(Globals.getThePrivateAccessibleNamesIf()); + if(i < (userRoles.size()-1)) + query.append((String)userRoles.get(i) + ","); + else if(i == (userRoles.size()-1)) + query.append((String)userRoles.get(i)+")"); + + } + //query.append(" ) "); + //query.append(" AND public_yn = 'N' order by 2 "); + + query.append(Globals.getTheGroupAccessibleNamesB()); + DataSet ds = DbUtils + .executeQuery(query.toString() ); + + for (int i = 0; i < ds.getRowCount(); i++) + groupReportIdNames + .add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1))); + } // catch(Exception e) {} + + return groupReportIdNames; + } // getGroupAccessibleReportIdNames + + + public static TableSource getTableSource(String tableName, String dBinfo, Vector userRoles, String userId, HttpServletRequest request) throws RaptorException { + try { + Vector tableSources = null; + if(Globals.getRestrictTablesByRole()) { + tableSources = getReportTableSources(userRoles, dBinfo, userId, request); + } else { + tableSources = getReportTableSources(dBinfo); + } + for (Iterator iter = getReportTableSources(dBinfo).iterator(); iter.hasNext();) { + TableSource tableSource = (TableSource) iter.next(); + if (tableSource.getTableName().equals(tableName)) + return tableSource; + } // for + } catch (RaptorException e) { + throw new RaptorException(e.getMessage(), e.getCause()); + } + + return null; + } + public static void refreshReportTableSources() { + reportTableSources = null; + } + + public static Vector getReportTableSources(String dBInfo) throws RaptorException { + if (reportTableSources == null) + /* try */{ + reportTableSources = new Vector(); + //String query = " SELECT table_name, display_name, pk_fields, web_view_action, large_data_source_yn, filter_sql FROM cr_table_source "; + String query = Globals.getTheReportTableSourcesA(); + if (dBInfo != null && !dBInfo.equals(AppConstants.DB_LOCAL)){ + //query += " where SOURCE_DB= '" + dBInfo + "'"; + query+=Globals.getTheReportTableSourcesWhere(); + query = query.replace("[dBInfo]", dBInfo); + } + else { + //query += " where SOURCE_DB is null or SOURCE_DB = '" + AppConstants.DB_LOCAL + // + "'"; + query+=Globals.getTheReportTableSourcesIf(); + query = query.replace("[AppConstants.DB_LOCAL]", AppConstants.DB_LOCAL); + } + //query += " ORDER BY table_name "; + query+=Globals.getTheReportTableSourcesElse(); + DataSet ds = DbUtils.executeQuery(query); + for (int i = 0; i < ds.getRowCount(); i++) + reportTableSources.add(new TableSource(ds.getString(i, 0), ds.getString(i, 1), + ds.getString(i, 2), ds.getString(i, 3), ds.getString(i, 4), ds + .getString(i, 5))); + } // catch(Exception e) {} + + return reportTableSources; + } // getReportTableSources + + public static Vector getReportTableSources(Vector userRoles, String dBInfo, String userId, HttpServletRequest request) + throws RaptorException { + if (!Globals.getRestrictTablesByRole()) + return getReportTableSources(dBInfo); + Vector userTableSources = new Vector(); + if (userRoles.size() > 0) + /* try */{ + StringBuffer sb = new StringBuffer(); + for (Iterator iter = userRoles.iterator(); iter.hasNext();) { + sb.append((sb.length() == 0) ? "(" : ", "); + sb.append(iter.next()); + } // for + sb.append(")"); + //StringBuffer query = new StringBuffer("SELECT ts.table_name, ts.display_name, ts.pk_fields, "); + // query.append(" ts.web_view_action, ts.large_data_source_yn, ts.filter_sql FROM cr_table_source ts "); + // query.append (" WHERE "); + StringBuffer query = new StringBuffer(Globals.grabTheReportTableA()); + //if(!(AppUtils.isAdminUser(userId) || AppUtils.isSuperUser(userId))) + // query.append (" (EXISTS (SELECT 1 FROM cr_table_role tr WHERE tr.table_name=ts.table_name AND tr.role_id IN "+sb.toString()+")) and "); + //+ " OR (NOT EXISTS (SELECT 1 FROM cr_table_role tr WHERE tr.table_name=ts.table_name)) "; + if (dBInfo != null && !dBInfo.equals(AppConstants.DB_LOCAL)){ + String d_sql = Globals.grabTheReportTableIf(); + d_sql = d_sql.replace("[dBInfo]", dBInfo); + //query.append( " ts.SOURCE_DB= '" + dBInfo + "'"); + query.append(d_sql); + } + else{ + //query.append(" (ts.SOURCE_DB is null or ts.SOURCE_DB = '"+ AppConstants.DB_LOCAL + "')"); + String d_sql = Globals.grabTheReportTableElse(); + d_sql = d_sql.replace("[AppConstants.DB_LOCAL]", AppConstants.DB_LOCAL); + query.append(d_sql); + } + if(!(AppUtils.isAdminUser(request) || AppUtils.isSuperUser(request))) { + //query.append(" minus "); + + // query.append(" SELECT ts.table_name, ts.display_name, ts.pk_fields, ts.web_view_action, "); + // query.append(" ts.large_data_source_yn, ts.filter_sql from cr_table_source ts where "); + // query.append(" table_name in (select table_name from cr_table_role where role_id not IN "+sb.toString()+") and "); + String e_sql = Globals.grabTheReportTableB(); + e_sql = e_sql.replace("[sb.toString()]", sb.toString()); + query.append(e_sql); + + if (dBInfo != null && !dBInfo.equals(AppConstants.DB_LOCAL)){ + + // query.append( " ts.SOURCE_DB= '" + dBInfo + "'"); + String d_sql = Globals.grabTheReportTableIf(); + d_sql = d_sql.replace("[dBInfo]", dBInfo); + query.append(d_sql); + } + else{ + //query.append(" (ts.SOURCE_DB is null or ts.SOURCE_DB = '"+ AppConstants.DB_LOCAL + "')"); + String d_sql = Globals.grabTheReportTableElse(); + d_sql = d_sql.replace("[AppConstants.DB_LOCAL]", AppConstants.DB_LOCAL); + query.append(d_sql); + } + } + //query.append(" ORDER BY 1 "); + query.append(Globals.grabTheReportTableC()); + DataSet ds = DbUtils.executeQuery(query.toString()); + for (int i = 0; i < ds.getRowCount(); i++) + userTableSources.add(new TableSource(ds.getString(i, 0), ds.getString(i, 1), + ds.getString(i, 2), ds.getString(i, 3), ds.getString(i, 4), ds + .getString(i, 5))); + } // catch(Exception e) {} + + return userTableSources; + } // getReportTableSources + + public static Vector getReportTableJoins() throws RaptorException { + if (reportTableJoins == null) + /* try */{ + reportTableJoins = new Vector(); + + //DataSet ds = DbUtils + // .executeQuery("SELECT src_table_name, dest_table_name, join_expr FROM cr_table_join"); + DataSet ds = DbUtils + .executeQuery(Globals.getTheReportTableCrJoin()); + for (int i = 0; i < ds.getRowCount(); i++) + reportTableJoins.add(new TableJoin(ds.getString(i, 0), ds.getString(i, 1), ds + .getString(i, 2))); + } // catch(Exception e) {} + + return reportTableJoins; + } // getReportTableJoins + + public static Vector getReportTableJoins(Vector userRoles) throws RaptorException { + if (!Globals.getRestrictTablesByRole()) + return getReportTableJoins(); + + Vector userTableJoins = new Vector(); + if (userRoles.size() > 0) + /* try */{ + StringBuffer sb = new StringBuffer(); + for (Iterator iter = userRoles.iterator(); iter.hasNext();) { + sb.append((sb.length() == 0) ? "(" : ", "); + sb.append(iter.next()); + } // for + sb.append(")"); + + /*DataSet ds = DbUtils + .executeQuery("SELECT tj.src_table_name, tj.dest_table_name, tj.join_expr FROM cr_table_join tj " + + "WHERE ((EXISTS (SELECT 1 FROM cr_table_role trs WHERE trs.table_name=tj.src_table_name AND trs.role_id IN " + + sb.toString() + + ")) " + + "OR (NOT EXISTS (SELECT 1 FROM cr_table_role trs WHERE trs.table_name=tj.src_table_name))) " + + "AND ((EXISTS (SELECT 1 FROM cr_table_role trd WHERE trd.table_name=tj.dest_table_name AND trd.role_id IN " + + sb.toString() + + ")) " + + "OR (NOT EXISTS (SELECT 1 FROM cr_table_role trd WHERE trd.table_name=tj.dest_table_name)))");*/ + + + String f_sql = Globals.getTheReportTableJoins(); + f_sql = f_sql.replace("[sb.toString()]", sb.toString()); + + DataSet ds = DbUtils + .executeQuery(f_sql); + + for (int i = 0; i < ds.getRowCount(); i++) + userTableJoins.add(new TableJoin(ds.getString(i, 0), ds.getString(i, 1), ds + .getString(i, 2))); + } // catch(Exception e) {} + + return userTableJoins; + } // getReportTableJoins + + private static void processDollarFields(Vector tableDbColumns) { + int i = 0; + while (i < tableDbColumns.size()) { + DBColumnInfo dbci = (DBColumnInfo) tableDbColumns.get(i); + if (dbci.getColName().equals("DL$MONTH")) { + tableDbColumns.remove(i); + dbci.setLabel("Data Month/Year"); + tableDbColumns.add(0, dbci); + i++; + } else if (dbci.getColName().indexOf('$') >= 0) + tableDbColumns.remove(i); + else + i++; + } // while + } // processDollarFields + + private static String generateReportTableDbUserColumnSQL(String tableName) { + StringBuffer sb = new StringBuffer(); + // sb.append("SELECT a.table_name, a.column_name, a.data_type, a.label "); + //sb.append(" FROM user_column_def a "); + // sb.append("WHERE a.table_name = '" + tableName.toUpperCase() + "' "); + // sb.append("ORDER BY a.column_id"); + + String sql = Globals.getGenerateReportTableCol(); + sql = sql.replace("[tableName.toUpperCase()]", tableName.toUpperCase()); + sb.append(sql); + + return sb.toString(); + }//generateReportTableDbUserColumnSQL + private static String generateReportTableDbColumnsSQL(String tableName, String maskSql) { + StringBuffer sb = new StringBuffer(); + //sb.append("SELECT utc.table_name, utc.column_name, utc.data_type, "); + sb.append(Globals.getGenerateDbUserSqlA()); + if (maskSql == null){ + //sb.append("utc.column_name label "); + sb.append(Globals.getGenerateDbUserSqlIf()); + } + else{ + //sb.append("nvl(x.label, utc.column_name) label "); + //sb.append("FROM user_tab_columns utc "); + sb.append(Globals.getGenerateDbUserSqlElse()); + } + if (maskSql != null) { + sb.append(", ("); + sb.append(maskSql); + sb.append(") AS x "); + } + //sb.append("WHERE utc.table_name = '" + tableName.toUpperCase() + "' "); + String g_sql = Globals.getGenerateDbUserSqlB(); + g_sql = g_sql.replace("[tableName.toUpperCase()]", tableName.toUpperCase()); + sb.append(g_sql); + if (maskSql != null){ + //sb.append(" AND utc.table_name = x.table_name AND utc.column_name = x.column_name "); + sb.append(Globals.getGenerateDbUserSqlC()); + } + //sb.append("ORDER BY utc.column_id"); + sb.append(Globals.getGenerateDbUserSqlD()); + //System.out.println(sb.toString()); + return sb.toString(); + } // generateReportTableDbColumnsSQL + + public static synchronized Vector getReportTableDbColumns(String tableName, + String remoteDbPrefix) throws RaptorException { + Vector tableDbColumns = null; + if(reportTableDbColumns!=null) + tableDbColumns = (Vector) reportTableDbColumns.get(tableName); + else + reportTableDbColumns = new HashMap(); + if (tableDbColumns == null) + /* try */{ + tableDbColumns = new Vector(); + + String maskSql = AppUtils.getReportDbColsMaskSQL(); + DataSet ds = null; + if(Globals.getUserColDef()) { + try { + ds = ConnectionUtils.getDataSet( + generateReportTableDbUserColumnSQL(tableName),AppConstants.DB_LOCAL); + } + catch (ReportSQLException ex) { + throw new ReportSQLException("No Such Table. Please create table or make user_column_def in raptor.properties as \"false\""); + } + + } + else if(maskSql!=null){ + try { + ds = ConnectionUtils.getDataSet( + generateReportTableDbColumnsSQL(tableName, maskSql), remoteDbPrefix); + } + catch(ReportSQLException ex){ + throw new ReportSQLException("Field related table is not present in the database. Please make \"use_field_table\"" + + " as \"no\" in the raptor_app_.properties");} + } + if (ds==null || ds.getRowCount() == 0) { + // In case there are no records in the FIELDS table + ds = ConnectionUtils.getDataSet(generateReportTableDbColumnsSQL(tableName, + null), remoteDbPrefix); + } + for (int i = 0; i < ds.getRowCount(); i++) + tableDbColumns.add(new DBColumnInfo(ds.getString(i, 0), ds.getString(i, 1), ds + .getString(i, 2), ds.getString(i, 3))); + + processDollarFields(tableDbColumns); + reportTableDbColumns.put(tableName, tableDbColumns); + } // catch(Exception e) {} + + return tableDbColumns; + } // getReportTableDbColumns + + public static synchronized String getReportTableDbColumnType(String tableName, + String columnName, String dbInfo) throws RaptorException { + for (Iterator iter = getReportTableDbColumns(tableName, dbInfo).iterator(); iter + .hasNext();) { + DBColumnInfo dbCol = (DBColumnInfo) iter.next(); + if (dbCol.getColName().equals(columnName)) + return dbCol.getColType(); + } // for + + return null; + } // getReportTableDbColumnType + + public static synchronized LookupDBInfo getLookupTable(String tableName, String fieldName) throws RaptorException { + if (reportFieldDbLookups == null) + try { + String sql = AppUtils.getReportDbLookupsSQL(); + + if (sql != null) { + DataSet ds = DbUtils.executeQuery(sql); + reportFieldDbLookups = new HashMap(); + for (int i = 0; i < ds.getRowCount(); i++) { + String tName = ds.getString(i, 0); + String fName = ds.getString(i, 1); + reportFieldDbLookups.put(tName + '|' + fName, new LookupDBInfo(tName, + fName, ds.getString(i, 2), ds.getString(i, 3), ds.getString(i, + 4))); + } // for + } // if + } catch (Exception e) { throw new RaptorException(e.getMessage(), e.getCause()); + } + + LookupDBInfo lookupDBInfo = null; + if (reportFieldDbLookups != null) + lookupDBInfo = (LookupDBInfo) reportFieldDbLookups + .get(tableName + '|' + fieldName); + + if (lookupDBInfo == null) + lookupDBInfo = new LookupDBInfo(tableName, fieldName, tableName, fieldName, + fieldName); + + return lookupDBInfo; + } // getLookupTable + + // public static void setRemoteDBPrefix (String remoteDBPrefix) { + // _remoteDBPrefix = remoteDBPrefix; + // } + // + // public static String getRemoteDBPrefix () { + // return _remoteDBPrefix; + // } + + public static void refreshAll() { + DataCache.dataViewActions = null; + DataCache.privateReportIdNames = null; + DataCache.publicReportIdNames = null; + DataCache.reportFieldDbLookups = null; + DataCache.reportTableDbColumns = null; + DataCache.reportTableJoins = null; + DataCache.reportTableSources = null; + AppUtils.resetUserCache(); + } +} // DataCache + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportHandler.java new file mode 100644 index 00000000..be950b99 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportHandler.java @@ -0,0 +1,6638 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * ReportHandler.java - This class is used to generate reports in Excel using POI and also to + * create ReportRuntime and ReportDefinition object using report id. + * ------------------------------------------------------------------------------------------- + * + * + * Changes + * ------- + * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 14-Jul-2009 : Version 8.4 (Sundar);
  • Signature for generating excel method has been changed to add the report name as sheet name.
  • + *
  • Dashboard reports can be downloaded with each report as a separate sheet.
  • + *
+ * 08-Jun-2009 : Version 8.3 (Sundar);
  • Short datatype is replaced with default integer datatype to create + * row as short is not expoting more than 32768 rows.
+ * + */ +package org.openecomp.portalsdk.analytics.model; + +import java.io.BufferedInputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TreeMap; +import java.util.Vector; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFDateUtil; +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFFooter; +import org.apache.poi.hssf.usermodel.HSSFHeader; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.hssf.util.Region; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.ss.usermodel.CreationHelper; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.Header; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFDataFormat; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.openecomp.portalsdk.analytics.controller.ErrorHandler; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.ReportSQLException; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.system.ExecuteQuery; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.ExcelColorDef; +import org.openecomp.portalsdk.analytics.util.HtmlStripper; +import org.openecomp.portalsdk.analytics.util.Log; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.view.ColumnHeader; +import org.openecomp.portalsdk.analytics.view.ColumnHeaderRow; +import org.openecomp.portalsdk.analytics.view.DataRow; +import org.openecomp.portalsdk.analytics.view.DataValue; +import org.openecomp.portalsdk.analytics.view.HtmlFormatter; +import org.openecomp.portalsdk.analytics.view.ReportData; +import org.openecomp.portalsdk.analytics.view.RowHeader; +import org.openecomp.portalsdk.analytics.view.RowHeaderCol; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.DataSourceType; +import org.openecomp.portalsdk.analytics.xmlobj.FormatList; +import org.openecomp.portalsdk.analytics.xmlobj.FormatType; +import org.openecomp.portalsdk.analytics.xmlobj.Reports; +import org.openecomp.portalsdk.analytics.xmlobj.SemaphoreList; +import org.openecomp.portalsdk.analytics.xmlobj.SemaphoreType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.lowagie.text.Document; +import com.lowagie.text.Paragraph; +import com.lowagie.text.html.simpleparser.HTMLWorker; +import com.lowagie.text.html.simpleparser.StyleSheet; +import com.lowagie.text.pdf.PdfPTable; +//import javax.servlet.RequestDispatcher; + +public class ReportHandler extends org.openecomp.portalsdk.analytics.RaptorObject { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportHandler.class); + + public ReportHandler() { + } + + private String SHEET_NAME = ""; + private static final String XML_ENCODING = "UTF-8"; + private static int font_size = 10; + private static int font_header_title_size = 12; + private static int font_header_descr_size = 9; + private static int font_footer_size = 9; + + + private HashMap loadStyles(ReportRuntime rr, HSSFWorkbook wb) { + HSSFCellStyle styleDefault = wb.createCellStyle(); + //System.out.println("Load Styles"); + // Style default will be normal with no background + HSSFFont fontDefault = wb.createFont(); + // The default will be plain . + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (font_size / 0.05)); + fontDefault.setFontName("Tahoma"); + + styleDefault.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDefault.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDefault.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDefault.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleDefault.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDefault.setFillPattern(HSSFCellStyle.NO_FILL); + styleDefault.setFont(fontDefault); + + HSSFCellStyle styleRed = wb.createCellStyle(); + styleRed.cloneStyleFrom(styleDefault); + styleRed.setFillForegroundColor((short)HSSFColor.RED.index); + styleRed.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + HSSFFont fontRed = wb.createFont(); + fontRed.setColor((short) HSSFColor.WHITE.index); + fontRed.setFontHeight((short) (font_size / 0.05)); + fontRed.setFontName("Tahoma"); + styleRed.setFont(fontRed); + + HSSFCellStyle styleYellow = wb.createCellStyle(); + styleYellow.cloneStyleFrom(styleDefault); + styleYellow.setFillForegroundColor((short)HSSFColor.YELLOW.index); + styleYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + HSSFFont fontYellow = wb.createFont(); + fontYellow.setColor((short) HSSFColor.BLACK.index); + fontYellow.setFontHeight((short) (font_size / 0.05)); + fontYellow.setFontName("Tahoma"); + styleYellow.setFont(fontYellow); + + HSSFCellStyle styleGreen = wb.createCellStyle(); + styleGreen.cloneStyleFrom(styleDefault); + styleGreen.setFillForegroundColor((short)HSSFColor.GREEN.index); + styleGreen.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + HSSFFont fontGreen = wb.createFont(); + fontGreen.setColor((short) HSSFColor.WHITE.index); + fontGreen.setFontHeight((short) (font_size / 0.05)); + fontGreen.setFontName("Tahoma"); + styleGreen.setFont(fontGreen); + + + ArrayList semColumnList = new ArrayList(); + List dsList = rr.getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType element = (DataSourceType) iter.next(); + List dcList = element.getDataColumnList().getDataColumn(); + for (Iterator iterator = dcList.iterator(); iterator.hasNext();) { + DataColumnType element1 = (DataColumnType) iterator.next(); + semColumnList.add(element1.getSemaphoreId()); + + } + } + SemaphoreList semList = rr.getSemaphoreList(); + HashMap hashMapStyles = new HashMap(); + HashMap hashMapFonts = new HashMap(); + hashMapFonts.put("default", fontDefault); + hashMapFonts.put("red", fontRed); + hashMapFonts.put("yellow", fontYellow); + hashMapFonts.put("green", fontGreen); + hashMapStyles.put("default", styleDefault); + hashMapStyles.put("red", styleRed); + hashMapStyles.put("yellow", styleYellow); + hashMapStyles.put("green", styleGreen); + HSSFCellStyle cellStyle = null; + if (semList == null || semList.getSemaphore() == null) { + return hashMapStyles; + } else { + for (Iterator iter = semList.getSemaphore().iterator(); iter.hasNext();) { + SemaphoreType sem = (SemaphoreType) iter.next(); + if(!semColumnList.contains(sem.getSemaphoreId())) continue; + //System.out.println("SemphoreId ----> " + sem.getSemaphoreId()); + FormatList fList = sem.getFormatList(); + List formatList = fList.getFormat(); + for (Iterator fIter = formatList.iterator(); fIter.hasNext();) { + FormatType fmt = (FormatType) fIter.next(); + if(fmt!=null){ + //if (fmt.getLessThanValue().length() > 0) { + cellStyle = wb.createCellStyle(); + HSSFFont cellFont = wb.createFont(); + //System.out.println("Format Id " + fmt.getFormatId()); + if (nvl(fmt.getBgColor()).length() > 0) { +// System.out.println("Load Styles " + +// fmt.getFormatId() +// + " " +fmt.getBgColor() + " " + +// ExcelColorDef.getExcelColor(fmt.getBgColor())); + cellStyle.setFillForegroundColor(ExcelColorDef.getExcelColor(fmt + .getBgColor())); + cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + } + if (nvl(fmt.getFontColor()).length() > 0) { + cellFont.setColor(ExcelColorDef.getExcelColor(fmt.getFontColor())); + } else + cellFont.setColor((short) HSSFFont.COLOR_NORMAL); + if (fmt.isBold()) + cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + if (fmt.isItalic()) + cellFont.setItalic(true); + if (fmt.isUnderline()) + cellFont.setUnderline(HSSFFont.U_SINGLE); + if(nvl(fmt.getFontFace()).length()>0) + cellFont.setFontName(fmt.getFontFace()); + else + cellFont.setFontName("Tahoma"); + //cellFont.setFontHeight((short) (10 / 0.05)); + + if(nvl(fmt.getFontSize()).length()>0) { + try { + //cellFont.setFontHeight((short) (Integer.parseInt(fmt.getFontSize()) / 0.05)); + cellFont.setFontHeight((short) (font_size/0.05)); + } catch(NumberFormatException e){ + cellFont.setFontHeight((short) (font_size / 0.05));//10 + } + } + else + cellFont.setFontHeight((short) (font_size / 0.05)); + cellStyle.setFont(cellFont); + cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); + cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); + cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); + cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); + cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); + hashMapStyles.put(fmt.getFormatId(), cellStyle); + } else { + hashMapStyles.put(fmt.getFormatId(), styleDefault); + hashMapStyles.put("default", styleDefault); + } + } + + } + } + return hashMapStyles; + } + + private void paintExcelParams(HSSFWorkbook wb,int rowNum,int col,ArrayList paramsList, String customizedParamInfo, HSSFSheet sheet, String reportTitle, String reportDescr) throws IOException { + //HSSFSheet sheet = wb.getSheet(getSheetName()); + int cellNum = 0; + HSSFRow row = null; + short s1 = 0, s2 = (short) 1; + HtmlStripper strip = new HtmlStripper(); + // Name Style + HSSFCellStyle styleName = wb.createCellStyle(); + //styleName.setFillBackgroundColor(HSSFColor.GREY_80_PERCENT.index); + styleName.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); + //styleName.setFillPattern(HSSFCellStyle.SPARSE_DOTS); + styleName.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleName.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleName.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleName.setBorderRight(HSSFCellStyle.BORDER_THIN); + styleName.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleName.setDataFormat((short)0); + HSSFFont font = wb.createFont(); + font.setFontHeight((short) (font_size / 0.05)); + font.setFontName("Tahoma"); + font.setColor(HSSFColor.BLACK.index); + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + styleName.setFont(font); + //Data Style + + // Create some fonts. + HSSFFont fontDefault = wb.createFont(); + // Initialize the styles & fonts. + // The default will be plain . + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (font_size / 0.05)); + fontDefault.setFontName("Tahoma"); + fontDefault.setItalic(true); + // Style default will be normal with no background + HSSFCellStyle styleValue = wb.createCellStyle(); + styleValue.setDataFormat((short)0); + styleValue.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleValue.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleValue.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleValue.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleValue.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleValue.setFillForegroundColor(HSSFColor.YELLOW.index); + styleValue.setFillPattern(HSSFCellStyle.NO_FILL); + styleValue.setFont(fontDefault); + HSSFCell cell = null; + HSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HSSFCellStyle.ALIGN_CENTER); +// styleDescription.setBorderBottom(HSSFCellStyle.BORDER_THIN); +// styleDescription.setBorderTop(HSSFCellStyle.BORDER_THIN); +// styleDescription.setBorderRight(HSSFCellStyle.BORDER_THIN); +// styleDescription.setBorderLeft(HSSFCellStyle.BORDER_THIN); + HSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) (font_size / 0.05)); //14 + fontDescr.setFontName("Tahoma"); + fontDescr.setColor(HSSFColor.BLACK.index); + fontDescr.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + styleDescription.setFont(font); + HSSFCell cellDescr = null; + int paramSeq = 0; + HSSFHeader header = sheet.getHeader(); + StringBuffer strBuf = new StringBuffer(); + if(!Globals.customizeFormFieldInfo() || customizedParamInfo.length()<=0) { + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + //System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); + if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if(paramSeq <= 1) { + row = sheet.createRow(++rowNum); + cell = row.createCell((short) 0); + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + cellDescr = row.createCell((short) 0); + cellDescr.setCellValue("Run-time Parameters"); + cellDescr.setCellStyle(styleDescription); + + + strBuf.append(reportTitle+"\n"); + //strBuf.append("Run-time Parameters\n"); + } + row = sheet.createRow(++rowNum); + cellNum = 0; + //System.out.println("RowNum " + rowNum + " " + value.getId() + " " +value.getName()); + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getId()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getName().replaceAll("~",",")); + cell.setCellStyle(styleValue); + + //strBuf.append(value.getId()+": "+ value.getName()+"\n"); + } + } //for + } else { + strBuf.append(reportTitle+"\n"); + Document document = new Document(); + document.open(); + HTMLWorker worker = new HTMLWorker(document); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("body", "leading", "16,0"); + ArrayList p = HTMLWorker.parseToList(new StringReader(customizedParamInfo), style); + String name = ""; + String token = ""; + String value = ""; + String s = ""; + PdfPTable pdfTable = null; + for (int k = 0; k < p.size(); ++k){ + if(p.get(k) instanceof Paragraph) + s = ((Paragraph)p.get(k)).toString(); + else { /*if ((p.get(k) instanceof PdfPTable))*/ + pdfTable = ((PdfPTable)p.get(k)); + } + //todo: Logic for parsing pdfTable should be added after upgrading to iText 5.0.0 + //s = Utils.replaceInString(s, ",", "|"); + s = s.replaceAll(",", "|"); + s = s.replaceAll("~", ","); + if(s.indexOf(":")!= -1) { + //System.out.println("|"+s+"|"); + row = sheet.createRow(++rowNum); + cell = row.createCell((short) 0); + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + cellDescr = row.createCell((short) 0); + cellDescr.setCellValue("Run-time Parameters"); + cellDescr.setCellStyle(styleDescription); + + //strBuf.append("Run-time Parameters\n"); + StringTokenizer st = new StringTokenizer(s.trim(), "|"); + while(st.hasMoreTokens()) { + token = st.nextToken(); + token = token.trim(); + if (!(token.trim().equals("|") || token.trim().equals("]]") || token.trim().equals("]") || token.trim().equals("[") )) { + if(token.endsWith(":")) { + name = token; + name = name.substring(0, name.length()-1); + if(name.startsWith("[")) + name = name.substring(1); + value = st.nextToken(); + if(nvl(value).endsWith("]"))value = nvl(value).substring(0, nvl(value).length()-1); + } /*else if(name != null && name.length() > 0) { + value = st.nextToken(); + if(value.endsWith("]]"))value = value.substring(0, value.length()-1); + }*/ + if(name!=null && name.trim().length()>0) { + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(name.trim()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.trim()); + cell.setCellStyle(styleValue); + //strBuf.append(name.trim()+": "+ value.trim()+"\n"); + } +/* if(token.endsWith(":") && (value!=null && value.trim().length()<=0) && (name!=null && name.trim().length()>0 && name.endsWith(":"))) { + name = name.substring(0, name.indexOf(":")+1); + //value = token.substring(token.indexOf(":")+1); + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(name.trim()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.trim()); + cell.setCellStyle(styleValue); + + //strBuf.append(name.trim()+": "+ value.trim()+"\n"); + value = ""; + name = ""; + } +*/ } + int cw = 0; + cw = name.trim().length() + 12; + // if(i!=cellWidth.size()-1) + if(sheet.getColumnWidth((short)0)< (short) name.trim().length()) + sheet.setColumnWidth((short)0, (short) name.trim().length()); + if(sheet.getColumnWidth((short)1)< (short) value.trim().length()) + sheet.setColumnWidth((short)1, (short) value.trim().length()); + name = ""; + value = ""; + + } + + try { + SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); + Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); + SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); + + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue("Report Date/Time"); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + + cell.setCellValue(dtimestamp.format(sysdate)+" "+Globals.getTimeZone()); + cell.setCellStyle(styleValue); + + } catch(Exception ex) { + //ex.printStackTrace(); + } + + + } + } + + +/* Iterator iter1 = paramsList.iterator(); + s1 = 0; s2 = (short)10; + if(iter1.hasNext()) { + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + cell.setCellValue(strip.stripHtml(customizedParamInfo)); + } +*/ +/* rowNum += 2; + row = sheet.createRow(rowNum);*/ + } // if + Iterator iterCheck = paramsList.iterator(); + if(iterCheck.hasNext()) { + rowNum += 2; + row = sheet.createRow(rowNum); + } + header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+" " + strBuf.toString()); + HSSFFooter footer = sheet.getFooter(); + footer.setLeft(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) 9)+ "Page " + HSSFFooter.page() + + " of " + HSSFFooter.numPages() ); + footer.setCenter(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) 9)+Globals.getFooterFirstLine()+"\n"+Globals.getFooterSecondLine()); + + } + + + + private int paintExcelData(HSSFWorkbook wb, int rowNum, int col, ReportData rd, + HashMap styles, ReportRuntime rr, HSSFSheet sheet, String sql_whole, OutputStream sos, HttpServletRequest request) throws RaptorException { + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + int returnValue = 0; + // HSSFSheet sheet = wb.getSheetAt(0); + HSSFCellStyle styleDefault = wb.createCellStyle(); + HSSFCellStyle styleNumber = wb.createCellStyle(); + HSSFCellStyle styleDecimalNumber = wb.createCellStyle(); + HSSFCellStyle styleCurrencyNumber = wb.createCellStyle(); + HSSFCellStyle styleCurrencyDecimalNumber = wb.createCellStyle(); + HSSFCellStyle styleDate = wb.createCellStyle(); + HtmlStripper strip = new HtmlStripper(); + //HSSFSheet sheet = wb.getSheet(getSheetName()); + HSSFCellStyle styleDataHeader = wb.createCellStyle(); + // style.setFillBackgroundColor(HSSFColor.AQUA.index); + styleDataHeader.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index); + styleDataHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + styleDataHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDataHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDataHeader.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDataHeader.setBorderRight(HSSFCellStyle.BORDER_THIN); + styleDataHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN); + HSSFFont font = wb.createFont(); + font.setFontHeight((short) (font_size / 0.05)); + font.setFontName("Tahoma"); + font.setColor(HSSFColor.BLACK.index); + styleDataHeader.setFont(font); + // Column Header + boolean firstPass = true; + ArrayList cellWidth = new ArrayList(); + java.util.HashMap dataTypeMap = new java.util.HashMap(); + int cellNum = 0; + rowNum += 0; + ColumnHeaderRow chr = null; + String title = ""; + +// System.out.println("***************** Size " + rd.reportColumnHeaderRows.size()); +// for (int i = 0; i < rd.reportColumnHeaderRows.size(); i++) { +// for (int j = 0; j < rd.reportColumnHeaderRows.getColumnHeaderRow(i).size(); j++) { +// System.out.println("Column Title " + rd.reportColumnHeaderRows.getColumnHeaderRow(i).getColumnHeader(j).getColumnTitle() +// + " " + rd.reportColumnHeaderRows.getColumnHeaderRow(i).getColumnHeader(j).isVisible()); +// } +// } +/* List dsList = rr.getDataSourceList().getDataSource(); + HashMap dataColumnTypeHashMap = new HashMap(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType element = (DataSourceType) iter.next(); + List dcList = element.getDataColumnList().getDataColumn(); + for (Iterator iterator = dcList.iterator(); iterator.hasNext();) { + DataColumnType element1 = (DataColumnType) iterator.next(); + dataTypeMap.put(element1.getColId(), element1.getColType()); + dataColumnTypeHashMap.put(element1.getColName(), element1); + } + } +*/ + int columnRows = rr.getVisibleColumnCount() - 1; + + HttpSession session = request.getSession(); + String drilldown_index = (String) session.getAttribute("drilldown_index"); + int index = 0; + try { + index = Integer.parseInt(drilldown_index); + } catch (NumberFormatException ex) { + index = 0; + } + String header = (String) session.getAttribute("TITLE_"+index); + String subtitle = (String) session.getAttribute("SUBTITLE_"+index); + if(nvl(header).length()>0) { + header = Utils.replaceInString(header, "
", " "); + header = Utils.replaceInString(header, "
", " "); + header = Utils.replaceInString(header, "
", " "); + header = strip.stripHtml(nvl(header).trim()); + subtitle = Utils.replaceInString(subtitle, "
", " "); + subtitle = Utils.replaceInString(subtitle, "
", " "); + subtitle = Utils.replaceInString(subtitle, "
", " "); + subtitle = strip.stripHtml(nvl(subtitle).trim()); + HSSFRow row = sheet.createRow(rowNum); + cellNum = 0; + row.createCell((short) cellNum).setCellValue(header); + sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (columnRows))); + rowNum += 1; + row = sheet.createRow(rowNum); + cellNum = 0; + row.createCell((short) cellNum).setCellValue(subtitle); + sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (columnRows))); + rowNum += 1; + } + + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + HSSFRow row = sheet.createRow(rowNum); + cellNum = -1; + /*if(rd.reportTotalRowHeaderCols!=null) { + cellNum +=1; + row.createCell((short) cellNum).setCellValue("Total"); + row.createCell((short) cellNum).setCellStyle(styleDataHeader); + //row.getCell((short) cellNum).setCellStyle(styleDataHeader); + }*/ + chr = rd.reportColumnHeaderRows.getNext(); + + if(nvl(sql_whole).length() <= 0 || (!rr.getReportType().equals(AppConstants.RT_LINEAR))) { + if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) + rd.reportRowHeaderCols.resetNext(0); + else + rd.reportRowHeaderCols.resetNext(1); + + for (; rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + + if (firstPass) { + title = rhc.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + row.createCell((short) cellNum).setCellValue(title); + //commented after bug reported by EPAT 01/17/2015 + //sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum+columnRows, (short) (cellNum))); + //System.out.println(" **************** Row Header Title " + rhc.getColumnTitle() + " " + cellNum + " " ); + //System.out.println(cellNum + " " + cellWidth.size()); + if (cellWidth.size() > 0 && cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < rhc + .getColumnTitle().length()) + cellWidth.set(cellNum, new Integer(title.length())); + } else + cellWidth.add(cellNum, new Integer(title.length())); + row.getCell((short) cellNum).setCellStyle(styleDataHeader); + } + + + } // for + + } + + firstPass = false; + +/* for(chr.resetNext(); chr.hasNext(); ) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + cellNum += 1; + row.createCell((short) cellNum).setCellValue(ch.getColumnTitle()); +// <%= ch.getColSpanHtml() %><%= ch.getRowSpanHtml() %>> +// <%= ch.getColumnTitleHtml() %> +// + } // if + } // for +*/ + + //cellNum = -1; + + +// Set mapSet = dataTypeMap.entrySet(); +// Map.Entry me; +// String element, value ; +// for (Iterator iter = mapSet.iterator(); iter.hasNext();) { +// me=(Map.Entry)iter.next(); +// element = (String) me.getKey(); +// value = (String) me.getValue(); +// System.out.println("DataTypeMap " + element + " " + value); +// } + + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + cellNum += 1; + + int colSpan = ch.getColSpan()-1; + title = ch.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + row.createCell((short) cellNum).setCellValue(title); + if(colSpan > 0) { + for ( int k = 1; k <= colSpan; k++ ) { + row.createCell((short) cellNum+k); + } + sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (cellNum+colSpan))); + } + + + +/* if (cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < ch + .getColumnTitle().length()) + cellWidth + .set((cellNum), new Integer(ch.getColumnTitle().length())); + } else + cellWidth.add((cellNum), new Integer(ch.getColumnTitle().length())); +*/ row.getCell((short) (cellNum)).setCellStyle(styleDataHeader); + for ( int k = 1; k <= colSpan; k++ ) { + row.getCell((short) (cellNum+k)).setCellStyle(styleDataHeader); + } + + if(colSpan > 0) + cellNum += colSpan; + } + } // for + +/* int cw = 0; + for (int i = 0; i < cellWidth.size(); i++) { + cw = ((Integer) cellWidth.get(i)).intValue() + 6; + sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); + } +*/ + rowNum += 1; + } // for + + + // Data + // Create some cell styles. + //HSSFCellStyle styleDefault = wb.createCellStyle(); + HSSFCellStyle styleCell = null; + + HSSFCellStyle styleTotal = wb.createCellStyle(); + HSSFCellStyle styleCurrencyTotal = wb.createCellStyle(); + HSSFCellStyle styleDefaultTotal = wb.createCellStyle(); + HSSFCellStyle styleCurrencyDecimalNumberTotal = wb.createCellStyle(); + HSSFCellStyle styleDecimalNumberTotal = wb.createCellStyle(); + HSSFCellStyle styleCurrencyNumberTotal = wb.createCellStyle(); + + + // Create some fonts. + HSSFFont fontDefault = wb.createFont(); + HSSFFont fontBold = wb.createFont(); + // Initialize the styles & fonts. + // The default will be plain . + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (font_size / 0.05)); + fontDefault.setFontName("Tahoma"); + + // The default will be bold black tachoma 10pt text. + fontBold.setColor((short) HSSFFont.COLOR_NORMAL); + fontBold.setFontHeight((short) (font_size / 0.05)); + fontBold.setFontName("Tahoma"); + fontBold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + // Style default will be normal with no background + styleDefault.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDefault.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDefault.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDefault.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleDefault.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDefault.setFillPattern(HSSFCellStyle.NO_FILL); + styleDefault.setFont(fontDefault); + styleDefault.setWrapText(true); + //Number + styleNumber.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleNumber.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleNumber.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleNumber.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleNumber.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleNumber.setFillPattern(HSSFCellStyle.NO_FILL); + styleNumber.setFont(fontDefault); + try { + styleNumber.setDataFormat((short)0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + } catch (Exception e) { + + } + //Decimal Number + styleDecimalNumber.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDecimalNumber.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDecimalNumber.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDecimalNumber.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleDecimalNumber.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDecimalNumber.setFillPattern(HSSFCellStyle.NO_FILL); + styleDecimalNumber.setFont(fontDefault); + styleDecimalNumber.setDataFormat((short)0x27);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + + //Decimal Number + styleDecimalNumberTotal.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDecimalNumberTotal.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDecimalNumberTotal.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDecimalNumberTotal.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleDecimalNumberTotal.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDecimalNumberTotal.setFillPattern(HSSFCellStyle.NO_FILL); + styleDecimalNumberTotal.setFont(fontBold); + styleDecimalNumberTotal.setDataFormat((short)0x27);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + + //CurrencyNumber + styleCurrencyDecimalNumber.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleCurrencyDecimalNumber.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleCurrencyDecimalNumber.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleCurrencyDecimalNumber.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleCurrencyDecimalNumber.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleCurrencyDecimalNumber.setFillPattern(HSSFCellStyle.NO_FILL); + styleCurrencyDecimalNumber.setFont(fontDefault); + styleCurrencyDecimalNumber.setDataFormat((short)8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + + //currency number bold + styleCurrencyDecimalNumberTotal.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleCurrencyDecimalNumberTotal.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleCurrencyDecimalNumberTotal.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleCurrencyDecimalNumberTotal.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleCurrencyDecimalNumberTotal.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleCurrencyDecimalNumberTotal.setFillPattern(HSSFCellStyle.NO_FILL); + styleCurrencyDecimalNumberTotal.setFont(fontBold); + styleCurrencyDecimalNumberTotal.setDataFormat((short)8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + + + //CurrencyNumber + styleCurrencyNumber.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleCurrencyNumber.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleCurrencyNumber.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleCurrencyNumber.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleCurrencyNumber.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleCurrencyNumber.setFillPattern(HSSFCellStyle.NO_FILL); + styleCurrencyNumber.setFont(fontDefault); + styleCurrencyNumber.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + + + //CurrencyNumber + styleCurrencyNumberTotal.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleCurrencyNumberTotal.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleCurrencyNumberTotal.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleCurrencyNumberTotal.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleCurrencyNumberTotal.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleCurrencyNumberTotal.setFillPattern(HSSFCellStyle.NO_FILL); + styleCurrencyNumberTotal.setFont(fontBold); + styleCurrencyNumberTotal.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + + //Date + styleDate.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDate.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDate.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDate.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleDate.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDate.setFillPattern(HSSFCellStyle.NO_FILL); + styleDate.setFont(fontDefault); + styleDate.setDataFormat((short)0xe);//HSSFDataFormat.getBuiltinFormat("m/d/yy")); + + // Style for Total will be Bold with normal font with no background + styleTotal.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleTotal.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleTotal.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleTotal.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleTotal.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleTotal.setFillPattern(HSSFCellStyle.NO_FILL); + styleTotal.setDataFormat((short)0x28);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + styleTotal.setFont(fontBold); + + styleCurrencyTotal.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleCurrencyTotal.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleCurrencyTotal.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleCurrencyTotal.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleCurrencyTotal.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleCurrencyTotal.setFillPattern(HSSFCellStyle.NO_FILL); + styleCurrencyTotal.setDataFormat((short)8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + styleCurrencyTotal.setFont(fontBold); + + styleDefaultTotal.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleDefaultTotal.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleDefaultTotal.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleDefaultTotal.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleDefaultTotal.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDefaultTotal.setFillPattern(HSSFCellStyle.NO_FILL); + styleDefaultTotal.setDataFormat((short)0x28); + ////styleDefaultTotal.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + styleDefaultTotal.setFont(fontBold); + + firstPass = true; + // Declare a row object reference. + HSSFRow row = null; + // Declare a cell object reference. + HSSFCell cell = null; + //HSSFCell cellNumber = null; + //HSSFCell cellCurrencyNumber = null; + //HSSFCell cellDate = null; + + //All the possible combinations of date format + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); + SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); + SimpleDateFormat YYYYMMDDDASHFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); + SimpleDateFormat DDMONYYHHMMFormat = new SimpleDateFormat("dd-MMM-yy HH:mm"); + SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); + SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); + SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat MMMMMDDYYYYHHMMSS = new SimpleDateFormat("MMMMM-dd-yyyy HH:mm:ss"); + + + + + ResultSet rs = null; + Connection conn = null; + Statement st = null; + ResultSetMetaData rsmd = null; + CreationHelper createHelper = wb.getCreationHelper(); + + if(nvl(sql_whole).length() >0 && rr.getReportType().equals(AppConstants.RT_LINEAR)) { + try { + conn = ConnectionUtils.getConnection(rr.getDbInfo()); + st = conn.createStatement(); + System.out.println("************* Map Whole SQL *************"); + System.out.println(sql_whole); + System.out.println("*****************************************"); + rs = st.executeQuery(sql_whole); + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + DataRow dr = null; + int j = 0; + int rowCount = 0; + while(rs.next()) { + rowCount++; + row = sheet.createRow(rowNum); + cellNum = -1; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnLabel(i).toUpperCase(), strip.stripHtml(rs.getString(i))); + } + rd.reportDataRows.resetNext(); + dr = rd.reportDataRows.getNext(); + j = 0; + //if(rowCount%1000 == 0) wb.write(sos); + + /*if(rd.reportTotalRowHeaderCols!=null) { + //cellNum = -1; + //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); + //if (firstPass) + // rhc.resetNext(); + //RowHeader rh = rhc.getRowHeader(rowCount-1); + row.createCell((short) cellNum).setCellValue(rowCount); + row.getCell((short) cellNum).setCellStyle(styleDefault); + if (firstPass) + cellWidth.add(cellNum, new Integer((rowCount+"").length())); + else + cellWidth.set(cellNum, new Integer((rowCount+"").length())); + + //} // for + }*/ + firstPass = false; + //cellNum = -1; + for (dr.resetNext(); dr.hasNext();j++) { + //for (chr.resetNext(); chr.hasNext();) { + //ColumnHeader ch = chr.getNext(); + styleCell = null; + DataValue dv = dr.getNext(); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) + styleCell = (HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default")); + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default")); + String value = nvl((String)colHash.get(dv.getColId().toUpperCase())); + + boolean bold = false; + + if(dv.isVisible()) { + cellNum += 1; + cell = row.createCell((short) cellNum); + //System.out.println("Stripping HTML 1"); + //cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); + String dataType = (String) (dataTypeMap.get(dv.getColId())); + //System.out.println("Value " + value + " " + (( dataType !=null && dataType.equals("DATE")) || (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date"))) ); + if (dataType!=null && dataType.equals("NUMBER")){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(dv.getDisplayValue()); + //cellCurrencyNumber = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")){ + cell.setCellValue(zInt); + }else{ + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (dv.getDisplayValue().startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = dv.getDisplayValue().trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 1 is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleCell!=null) { + styleCell.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + //cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if(styleCell!=null) { + styleCell.setDataFormat((short)0x28);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(value); + } + + } + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (dv.getDisplayValue().startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT is "+tempInt); + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleCell!=null) { + styleCell.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleCell!=null) { + styleCell.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + + + } + //int temp = Integer.parseInt(value.trim()); + // cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + } + } + } + + }else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || + (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { + //cellDate = row.createCell((short) cellNum); + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yy")); + + if(styleCell!=null) { + styleCell.setDataFormat((short) 0xe);//HSSFDataFormat.getBuiltinFormat("m/d/yy")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDate); + //String MY_DATE_FORMAT = "yyyy-MM-dd"; + //value = nvl(value).length()<=0?nvl(dv.getDisplayValue()):value; + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy")); + flag = 1; + } + if(date==null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d")); + flag = 1; + } + if(date==null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d h:mm:ss")); //yyyy-MM-dd HH:mm:ss + flag = 1; + } + if(date==null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm yyyy")); + flag = 1; + } + if(date==null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/yyyy")); + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/d/yyyy")); + flag = 1; + } + if(date==null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/yyyy")); + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm:ss")); + flag = 1; + } + if(date==null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d")); + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm:ss")); + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm")); + flag = 1; + } + if(date==null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yy h:mm")); + flag = 1; + } + if(date==null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + + if(date!=null) { + //System.out.println("ExcelDate " + HSSFDateUtil.getExcelDate(date)); + cell.setCellValue(HSSFDateUtil.getExcelDate(date)); + try { + String str = cell.getStringCellValue(); + } catch (IllegalStateException ex) { /*cell.getCellStyle().setDataFormat((short)0);*/cell.setCellValue(value);} + } else { + /*cell.getCellStyle().setDataFormat((short)0);*/ + cell.setCellValue(value); + } + //cellDate.setCellValue(date); + //cellDate.setCellValue(value); //cellDate.setCellValue(date); + //cellDate.setCellValue(dv.getDisplayValue()); + + }else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(dv.getDisplayValue()); + cell = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")){ + cell.setCellValue(zInt); + }else{ + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 2IF is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleCell!=null) { + styleCell.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + + + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(","))!= -1){ + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if(styleCell!=null) { + styleCell.setDataFormat((short)0x28 );//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDoubleStr); + } + } + + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT 2 is "+tempInt); + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleCell!=null) { + styleCell.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleCell!=null) { + styleCell.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + } + //int temp = Integer.parseInt(dv.getDisplayValue().trim()); + // cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); + //} + } else { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + } + } + } + + + } + else { + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(strip.stripHtml(value)); + } + + //if (!(value.equals(""))){ + //int temp = Integer.parseInt(value.trim()); + //cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + //HSSFCellStyle styleFormat = null; + //HSSFCellStyle numberStyle = null; + //HSSFFont formatFont = null; + //short fgcolor = 0; + //short fillpattern = 0; + if (cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < dv + .getDisplayValue().length()) + cellWidth.set((cellNum), + (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); + } else + cellWidth.add((cellNum), (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); + //System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + dv.getColName() ); + if (dv.isBold()) { + if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + cell.setCellStyle(styleCurrencyTotal); + } + else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); + continue; + } + //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default"))); + } //else if (bold == false) + //cell.setCellStyle(styleDefault); + } // dv.isVisible + } + rowNum += 1; + + } + + int cw = 0; + for (int i = 0; i < cellWidth.size(); i++) { + cw = ((Integer) cellWidth.get(i)).intValue() + 12; + // if(i!=cellWidth.size()-1) + sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); + // else + // sheet.setColumnWidth((short) (i + 1), (short) ((cw * 10) / + // ((double) 1 / 20))); + } + + // To Display Total Values for Linear report + if(rd.reportDataTotalRow!=null) { + row = sheet.createRow(rowNum); + cellNum = -1; + rd.reportTotalRowHeaderCols.resetNext(); + //for (rd.reportTotalRowHeaderCols.resetNext(); rd.reportTotalRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); + //} + + rd.reportDataTotalRow.resetNext(); + DataRow drTotal = rd.reportDataTotalRow.getNext(); + //cellNum = -1; + + drTotal.resetNext(); + drTotal.getNext(); + for (; drTotal.hasNext();) { + cellNum += 1; + cell = row.createCell((short) cellNum); + DataValue dv = drTotal.getNext(); + String value = dv.getDisplayValue(); + cell.setCellValue(value); + boolean bold = false; + if (dv.isBold()) { + if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + cell.setCellStyle(styleCurrencyTotal); + } else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + } + } + + } catch (SQLException ex) { + ex.printStackTrace(); + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + if(!(ex.getCause() instanceof java.net.SocketException) ) + throw new RaptorException (ex); + } finally { + try { + if(conn!=null) + conn.close(); + if(st!=null) + st.close(); + if(rs!=null) + rs.close(); + } catch (SQLException ex) { + throw new RaptorException(ex); + } + } + + /*if(Globals.getShowDisclaimer() && !Globals.disclaimerPositionedTopInCSVExcel()) { + rowNum += 1; + row = sheet.createRow(rowNum); + cellNum = 0; + String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); + row.createCell((short) cellNum).setCellValue(disclaimer); + sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (columnRows))); + rowNum += 1; + }*/ + } else { + if(rr.getReportType().equals(AppConstants.RT_LINEAR)) { + int rowCount = 0; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + DataRow dr = rd.reportDataRows.getNext(); + //List l = rd.getReportDataList(); + //for (int dataRow = 0; dataRow < l.size(); dataRow++) { + rowCount++; + + + //DataRow dr = (DataRow) l.get(dataRow); + row = sheet.createRow(rowNum); + + cellNum = -1; + + if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) { + rd.reportRowHeaderCols.resetNext(0); + if(rd.reportTotalRowHeaderCols!=null) { + //cellNum = -1; + //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { + //cellNum += 1; + //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); + //if (firstPass) + // rhc.resetNext(); + //RowHeader rh = rhc.getRowHeader(rowCount-1); + //row.createCell((short) cellNum).setCellValue(rowCount); + //row.getCell((short) cellNum).setCellStyle(styleDefault); + //if (firstPass) + //cellWidth.add(cellNum, new Integer((rowCount+"").length())); + //else + //cellWidth.set(cellNum, new Integer((rowCount+"").length())); + + //} // for + } + + } else { + rd.reportRowHeaderCols.resetNext(0); + } + for (; rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + row.getCell((short) cellNum).setCellStyle(styleDefault); + if (cellWidth.size() > 0) { + if (((Integer) cellWidth.get(cellNum)).intValue() < rh.getRowTitle() + .length()) + cellWidth.set(cellNum, new Integer(rh.getRowTitle().length())); + } else + cellWidth.add(cellNum, new Integer(rh.getRowTitle().length())); + + } // for + firstPass = false; + //cellNum = -1; + int j = 0; + + for (dr.resetNext(); dr.hasNext();j++) { + DataValue dv = dr.getNext(); + styleCell = null; + boolean bold = false; + String value = nvl(dv.getDisplayValue()); + value = strip.stripHtml(value); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) + styleCell = (HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default")); + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default")); + + if(dv.isVisible()) { + cellNum += 1; + cell = row.createCell((short) cellNum); + //System.out.println("Stripping HTML 1"); + //cell.setCellValue(strip.stripHtml(value)); + String dataType = (String) (dataTypeMap.get(dv.getColId())); + //System.out.println(" The Display Value is ********"+value + " " + dv.getDisplayTotal() + " " + dv.getColName()); + + if (dataType!=null && dataType.equals("NUMBER")){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(value); + //cellCurrencyNumber = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")){ + cell.setCellValue(zInt); + }else{ + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 1 is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleCell!=null) { + styleCell.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if(styleCell!=null) { + styleCell.setDataFormat((short) 0x28);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(value); + } + + } + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT is "+tempInt); + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleCell!=null) { + styleCell.setDataFormat((short)6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleCell!=null) { + styleCell.setDataFormat((short)0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + + + } + //int temp = Integer.parseInt(value.trim()); + // cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + } + } + } + + }else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || + (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { + //cellDate = row.createCell((short) cellNum); + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yy")); + + if(styleCell!=null) { + styleCell.setDataFormat((short)0xe); //HSSFDataFormat.getBuiltinFormat("m/d/yy")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDate); + //String MY_DATE_FORMAT = "yyyy-MM-dd"; + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if(date==null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d")); + flag = 1; + } + if(date==null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d h:mm:ss")); //yyyy-MM-dd HH:mm:ss + flag = 1; + } + if(date==null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm yyyy")); + flag = 1; + } + if(date==null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/yyyy")); + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/d/yyyy")); + flag = 1; + } + if(date==null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/yyyy")); + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm:ss")); + flag = 1; + } + if(date==null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d")); + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm:ss")); + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm")); + flag = 1; + } + if(date==null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yy h:mm")); + flag = 1; + } + if(date==null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + + if(date!=null) { + //System.out.println("ExcelDate " + HSSFDateUtil.getExcelDate(date)); + cell.setCellValue(HSSFDateUtil.getExcelDate(date)); + try { + String str = cell.getStringCellValue(); + } catch (IllegalStateException ex) { /*cell.getCellStyle().setDataFormat((short)0);*/cell.setCellValue(value);} + } else { + /*cell.getCellStyle().setDataFormat((short)0);*/ + cell.setCellValue(value); + } + //cellDate.setCellValue(date); + //cellDate.setCellValue(value); + + }else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(value); + cell = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")){ + cell.setCellValue(zInt); + }else{ + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 2IF is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleCell!=null) { + styleCell.setDataFormat((short)8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + + + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(","))!= -1){ + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if(styleCell!=null) { + styleCell.setDataFormat((short) 0x28); // for decimal + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDoubleStr); + } + } + + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT 2 is "+tempInt); + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleCell!=null) { + styleCell.setDataFormat((short) 6); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleCell!=null) { + styleCell.setDataFormat((short) 0x26); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + } + //int temp = Integer.parseInt(value.trim()); + // cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + } else { + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + } + } + } + + + } + else { + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); + if(styleCell!=null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(strip.stripHtml(value)); + } + + //if (!(value.equals(""))){ + //int temp = Integer.parseInt(value.trim()); + //cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + //HSSFCellStyle styleFormat = null; + //HSSFCellStyle numberStyle = null; + //HSSFFont formatFont = null; + //short fgcolor = 0; + //short fillpattern = 0; + if (cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < dv + .getDisplayValue().length()) + cellWidth.set((cellNum), + (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); + } else + cellWidth.add((cellNum), (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); + //System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + dv.getColName() ); + if (dv.isBold()) { + if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + cell.setCellStyle(styleCurrencyTotal); + } + else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); + continue; + } + //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + // cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default"))); + } //else if (bold == false) + //cell.setCellStyle(styleDefault); + } // if (dv.isVisible) + } // for + + /*for (int tmp=0; tmp rowNames = dr.getRowValues(); + for(dr.resetNext(); dr.hasNext(); rowCount++ ) { + if(first) { + if(rowNames!=null) { + for(int i=0; i0) { + cellNum += 1; + row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue())); + //row.getCell((short) cellNum).setCellStyle(styleDefault); + if(nvl(dv.getFormatId()).length()>0) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default"))); + else + row.setRowStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); + } else { + cellNum += 1; + row.createCell((short) cellNum).setCellValue(strip.stripHtml(value)); + row.getCell((short) cellNum).setCellStyle(styleDefault); + } // end + value = dv.getDisplayValue(); + if(value.indexOf("|#")!=-1) { + String color = value.substring(value.indexOf("|")+1); + if(color.equals("#FF0000")) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("red")); + else if (color.equals("#008000")) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("green")); + else if (color.equals("#FFFF00")) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("yellow")); + else { + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("default")); + } + + } + } + } + rowNum += 1; + int cw = 0; + for (int i = 0; i < cellWidth.size(); i++) { + cw = ((Integer) cellWidth.get(i)).intValue() + 12; + // if(i!=cellWidth.size()-1) + sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); + // else + // sheet.setColumnWidth((short) (i + 1), (short) ((cw * 10) / + // ((double) 1 / 20))); + } + + + } // for + + } + + + } + + String footer = (String) session.getAttribute("FOOTER_"+index); + if(nvl(footer).length()>0) { + footer = Utils.replaceInString(footer, "
", " "); + footer = Utils.replaceInString(footer, "
", " "); + footer = Utils.replaceInString(footer, "
", " "); + footer = strip.stripHtml(nvl(footer).trim()); + row = sheet.createRow(rowNum); + cellNum = 0; + row.createCell((short) cellNum).setCellValue(footer); + sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (columnRows))); + //sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum+columnRows, (short) (cellNum))); + rowNum += 1; + } + + if(Globals.getShowDisclaimer() && !Globals.disclaimerPositionedTopInCSVExcel()) { + + rowNum += 1; + row = sheet.createRow(rowNum); + cellNum = 0; + String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); + row.createCell((short) cellNum).setCellValue(disclaimer); + sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (columnRows))); + rowNum += 1; + } + + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + return returnValue; + + } + + private void paintExcelHeader(HSSFWorkbook wb, int rowNum, int col, String reportTitle, + String reportDescr, HSSFSheet sheet) { + short s1 = 0, s2 = (short) (col-1); + rowNum += 1; + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + HSSFRow row = null, row1 = null; + + row = sheet.createRow(rowNum); + // Header Style + HSSFCellStyle styleHeader = wb.createCellStyle(); + styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER); + HSSFFont font = wb.createFont(); + font.setFontHeight((short) (font_header_title_size / 0.05)); //14 + font.setFontName("Tahoma"); + font.setColor(HSSFColor.BLACK.index); + styleHeader.setFont(font); + + HSSFCell cell = row.createCell((short) 0); + cell.setCellValue(reportTitle); + cell.setCellStyle(styleHeader); + HSSFHeader header = sheet.getHeader(); + header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+" " + reportTitle); + + //header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+reportTitle+"\n"+((Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0)?reportDescr:"")); + + // Report Description + if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { + rowNum += 1; + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + HSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HSSFCellStyle.ALIGN_CENTER); + HSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) font_header_descr_size); + fontDescr.setFontName("Tahoma"); + fontDescr.setColor(HSSFColor.BLACK.index); + styleDescription.setFont(fontDescr); + HSSFCell cellDescr = row.createCell((short) 0); + cellDescr.setCellValue(reportDescr); + cellDescr.setCellStyle(styleHeader); + } + + if(Globals.disclaimerPositionedTopInCSVExcel()) { + rowNum += 1; + row = sheet.createRow(rowNum); + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + HSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HSSFCellStyle.ALIGN_CENTER); + HSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) (font_size / 0.05)); //14 + fontDescr.setFontName("Tahoma"); + fontDescr.setColor(HSSFColor.BLACK.index); + fontDescr.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + styleDescription.setFont(fontDescr); + HSSFCell cellDescr = row.createCell((short) 0); + String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); + cellDescr.setCellValue(disclaimer); + cellDescr.setCellStyle(styleDescription); + } + + rowNum += 1; + row = sheet.createRow(rowNum); + // System.out.println(" Last Row " + wb.getSheetAt(0).getLastRowNum()); + } + + private void paintExcelFooter(HSSFWorkbook wb, int rowNum, int col, HSSFSheet sheet) { + logger.debug(EELFLoggerDelegate.debugLogger, ("excel footer")); + //HSSFSheet sheet = wb.getSheet(getSheetName()); + HSSFFooter footer = sheet.getFooter(); + footer.setLeft(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) font_footer_size)+ "Page " + HSSFFooter.page() + + " of " + HSSFFooter.numPages() ); + footer.setCenter(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) font_footer_size)+Globals.getFooterFirstLine()+"\n"+Globals.getFooterSecondLine()); + //footer.setCenter(HSSFFooter.font("Tahoma", "Italic")+ HSSFFooter.fontSize((short) 16))+Globals.getFooterSecondLine()); +/* footer.font("Tahoma"); + short s1 = 0, s2 = (short) (col-1); + rowNum += 1; + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + HSSFRow row = null, row1 = null; + + row = sheet.createRow(rowNum); + // Header Style + HSSFCellStyle styleFooter = wb.createCellStyle(); + styleFooter.setAlignment(HSSFCellStyle.ALIGN_CENTER); + HSSFFont font = wb.createFont(); + font.setFontHeight((short) (10 / 0.05)); + font.setFontName("Tahoma"); + font.setColor(HSSFColor.BLACK.index); + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + styleFooter.setFont(font); + + HSSFCell cell = row.createCell((short) 0); + debugLogger.debug(Globals.getFooterFirstLine()); + cell.setCellValue(Globals.getFooterFirstLine()); + cell.setCellStyle(styleFooter); + + rowNum += 1; + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + row = sheet.createRow(rowNum); + cell = row.createCell((short) 0); + debugLogger.debug(Globals.getFooterSecondLine()); + cell.setCellValue(Globals.getFooterSecondLine()); + cell.setCellStyle(styleFooter); +*/ + logger.debug(EELFLoggerDelegate.debugLogger, ("Done")); + } + + public String saveAsExcelFile(HttpServletRequest request, ReportData rd, + ArrayList reportParamNameValues, String reportTitle, String reportDescr) { + return saveAsExcelFile(request, rd, reportParamNameValues, reportTitle, reportDescr, 2); //2 denotes ReportRuntime object should be taken from session. + } + public String saveAsExcelFile(HttpServletRequest request, ReportData rd, + ArrayList reportParamNameValues, String reportTitle, String reportDescr, int requestFlag) { + setSheetName(Globals.getSheetName()); + try { + ReportRuntime rr; + if(requestFlag == 2) + rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + else + rr = (ReportRuntime) request.getAttribute( + AppConstants.SI_REPORT_RUNTIME); + HSSFWorkbook wb = new HSSFWorkbook(); + HashMap styles = new HashMap(); + if (rr != null) + styles = loadStyles(rr, wb); + String xlsFName = AppUtils.generateUniqueFileName(request, rr.getReportName(), AppConstants.FT_XLS); + logger.debug(EELFLoggerDelegate.debugLogger, ("Xls File name " + + AppUtils.getTempFolderPath() + + xlsFName)); + FileOutputStream xlsOut = new FileOutputStream(AppUtils.getTempFolderPath() + + xlsFName); + // BufferedWriter xlsOut = new BufferedWriter(new + // FileWriter(AppUtils + // .getTempFolderPath() + // + xlsFName)); + + int col = 0; + //System.out.println("Row Header Count " + rd.reportRowHeaderCols.getRowCount()); + //System.out.println("Total Count " + rd.getTotalColumnCount()); + + if (!rd.reportRowHeaderCols.hasNext()) + col = rd.getTotalColumnCount(); + else + col = rd.getTotalColumnCount(); + int rowNum = 0; + HSSFSheet sheet = wb.createSheet(getSheetName()); + + if (Globals.getPrintTitleInDownload()&& reportTitle != null ) { + paintExcelHeader(wb, rowNum, col, reportTitle, reportDescr, sheet); + rowNum = sheet.getLastRowNum(); + } else + rowNum = 0; + if (Globals.getPrintParamsInDownload() && rr.getParamNameValuePairsforPDFExcel(request, 1) != null) { + paintExcelParams(wb,rowNum,col,rr.getParamNameValuePairsforPDFExcel(request, 1), rr.getFormFieldComments(request), sheet, reportTitle, reportDescr); + } // if + rowNum = sheet.getLastRowNum(); + //System.out.println(" rowNum after Params " + rowNum); + paintExcelData(wb, rowNum, col, rd, styles,rr, sheet, "", xlsOut, request); + if (Globals.getPrintFooterInDownload() ) { + rowNum = sheet.getLastRowNum(); + rowNum += 2; + paintExcelFooter(wb, rowNum, col, sheet); + } + //response.setContentType("application/vnd.ms-excel"); + //response.setHeader("Content-disposition", "attachment;filename=download_all_" + // + user_id + ".xls"); + wb.write(xlsOut); + xlsOut.flush(); + xlsOut.close(); + return xlsFName; + } catch (Exception e) { + e.printStackTrace(); + (new ErrorHandler()).processError(request, "Exception saving data to EXCEL file: " + + e.getMessage()); + return null; + } + } // saveAsExcelFile + + public void createExcelFileContent(Writer out, ReportData rd, ReportRuntime rr, HttpServletRequest request, + HttpServletResponse response, String user_id, int type) throws IOException, RaptorException { + // Adding utility for downloading Dashboard reports. + + HashMap styles = new HashMap(); + HttpSession session = request.getSession(); + ServletOutputStream sos = null; + BufferedInputStream buf = null; + HSSFWorkbook wb = null; +// if(session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) +// ReportRuntime rrDashboard = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + String formattedDate = ""; + String xlsFName = ""; + int returnValue = 0; + boolean isDashboard = false; + if ((session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) { + isDashboard = true; + } + if(isDashboard) { + try { + formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + xlsFName = "dashboard"+formattedDate+user_id+".xls"; + + FileInputStream xlsIn = null; + POIFSFileSystem fileSystem = null; + buf = null; + FileOutputStream xlsOut = null; + + +/* try { + xlsIn = new FileInputStream (AppUtils.getTempFolderPath() + + xlsFName); + } + catch (FileNotFoundException e) { + System.out.println ("File not found in the specified path."); + e.printStackTrace (); + } + if(xlsIn != null) { + fileSystem = new POIFSFileSystem (xlsIn); + wb = new HSSFWorkbook(fileSystem); + } else { + xlsOut = new FileOutputStream(AppUtils.getTempFolderPath() + + xlsFName); + wb = new HSSFWorkbook(); + } +*/ + + Map reportRuntimeMap = null; + Map reportDataMap = null; + //Map reportDisplayTypeMap = null; + reportRuntimeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + reportDataMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + //reportDisplayTypeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI); + HSSFSheet sheet = null; + if(reportRuntimeMap!=null) { + //ServletOutputStream sos = response.getOutputStream(); + Set setReportRuntime = reportRuntimeMap.entrySet(); + Set setReportDataMap = reportDataMap.entrySet(); + Iterator iter2 = setReportDataMap.iterator(); + int count = 0; + + for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { + count++; + try { + xlsIn = new FileInputStream (AppUtils.getTempFolderPath() + + xlsFName); + } + catch (FileNotFoundException e) { + System.out.println ("File not found in the specified path."); + //e.printStackTrace (); + } + if(xlsIn != null) { + fileSystem = new POIFSFileSystem (xlsIn); + wb = new HSSFWorkbook(fileSystem); + xlsOut = new FileOutputStream(AppUtils.getTempFolderPath() + + xlsFName); + } else { + xlsOut = new FileOutputStream(AppUtils.getTempFolderPath() + + xlsFName); + wb = new HSSFWorkbook(); + } + + Map.Entry entryData = (Entry) iter2.next(); + Map.Entry entry = (Entry) iter.next(); + //String rep_id = (String) entry.getKey(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + ReportData rdDashRep = (ReportData) entryData.getValue(); + //styles = loadStyles(rrDashRep, wb); + int col = 0; + String reportTitle = (nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName()); + String reportDescr = rrDashRep.getReportDescr(); + if (!rdDashRep.reportRowHeaderCols.hasNext()) + col = rdDashRep.getTotalColumnCount(); + else + col = rdDashRep.getTotalColumnCount(); + if(col==0) col=10; + int rowNum = 0; + String formattedReportName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); + + try { + sheet = wb.createSheet(formattedReportName); + sheet.getPrintSetup().setLandscape(true); + styles = loadStyles(rrDashRep, wb); + } catch (IllegalArgumentException ex) { wb.write(xlsOut);xlsOut.flush();xlsOut.close();continue;} + + if (Globals.getPrintTitleInDownload()&& reportTitle != null ) { + paintExcelHeader(wb, rowNum, col, reportTitle, reportDescr, sheet); + rowNum = sheet.getLastRowNum(); + } else + rowNum = 0; + //getting ReportRuntime object from session + if (Globals.getPrintParamsInDownload() && rrDashRep.getParamNameValuePairsforPDFExcel(request, 1) != null) { + if(count > 1 && Globals.showParamsInAllDashboardReports()) + paintExcelParams(wb,rowNum,col,rrDashRep.getParamNameValuePairsforPDFExcel(request, 1), rrDashRep.getFormFieldComments(request), sheet, reportTitle, reportDescr); + else if (count == 1) + paintExcelParams(wb,rowNum,col,rrDashRep.getParamNameValuePairsforPDFExcel(request, 1), rrDashRep.getFormFieldComments(request), sheet, reportTitle, reportDescr); + } // if + rowNum = sheet.getLastRowNum(); + String sql_whole = rrDashRep.getWholeSQL(); + returnValue = paintExcelData(wb, rowNum, col, rdDashRep, styles,rrDashRep, sheet, sql_whole, xlsOut, request); + if( returnValue == 0 ) { + if (Globals.getPrintFooterInDownload()) { + rowNum = sheet.getLastRowNum(); + rowNum += 2; + paintExcelFooter(wb, rowNum, col, sheet); + } + //wb.write(sos); + wb.write(xlsOut); + //TODO Remove comment + xlsOut.flush(); + xlsOut.close(); + wb = null; + } else { + //xlsOut.flush(); + //xlsOut.close(); + //response.reset(); + //response.setContentType("application/vnd.ms-excel"); +// RequestDispatcher dispatcher = request.getRequestDispatcher("raptor.htm?r_action=report.message"); +// request.setAttribute("message", Globals.getUserDefinedMessageForMemoryLimitReached()); +// try { +// dispatcher.forward(request, response); +// } catch (ServletException ex) {} + } + } + + response.reset(); + response.setContentType("application/vnd.ms-excel"); + response.setHeader("Content-disposition", "attachment;filename="+"dashboard"+formattedDate+user_id+".xls"); + sos = response.getOutputStream(); + xlsIn = new FileInputStream (AppUtils.getTempFolderPath() + + xlsFName); + buf = new BufferedInputStream(xlsIn); + int readBytes = 0; + byte [] bOut = new byte [4096]; + //read from the file; write to the ServletOutputStream + //while ((readBytes = buf.read()) != -1) + while ((readBytes = buf.read (bOut, 0, 4096))> 0) { + buf.available(); + sos.write (bOut, 0, readBytes); + } + + //sos.write(readBytes); + } + } catch (IOException ex) { ex.printStackTrace(); throw ex;} + + finally { + if (sos != null) + sos.close(); + if (buf != null) + buf.close(); + } + + File f = new File (AppUtils.getTempFolderPath() + + xlsFName); + if(f.exists()) f.delete(); + + } else { + wb = new HSSFWorkbook(); + // PrintWriter xlsOut = new PrintWriter(out).; + setSheetName(Globals.getSheetName()); + //ServletOutputStream sos = response.getOutputStream(); + //PrintWriter outWriter = response.getWriter(); + if (rr != null) + styles = loadStyles(rr, wb); + /* int col = 0; + if (!rd.reportRowHeaderCols.hasNext()) + col = rd.getTotalColumnCount(); + else + col = rd.getTotalColumnCount() + 1; + int rowNum = 0; + String reportTitle = rr.getReportName(); + String reportDescr = rr.getReportDescr(); + // if (Globals.getPrintTitleInDownload() && reportTitle != null) { + HSSFSheet sheet = wb.createSheet(getSheetName()); + System.out.println(" Title " + Globals.getPrintTitleInDownload()); + + if (Globals.getPrintTitleInDownload()&& reportTitle != null ) { + paintExcelHeader(wb, rowNum, col, reportTitle, reportDescr); + rowNum = wb.getSheetAt(0).getLastRowNum(); + } else + rowNum = 0; + System.out.println(" Params " + Globals.getPrintParamsInDownload()); + if (Globals.getPrintParamsInDownload() && rr.getParamNameValuePairs() != null) { + paintExcelParams(wb,rowNum,col,rr.getParamNameValuePairs()); + } // if + paintExcelData(wb, rowNum, col, rd, styles); + rowNum = wb.getSheetAt(0).getLastRowNum(); + */ + int col = 0; + //System.out.println("Row Header Count " + rd.reportRowHeaderCols.getRowCount()); + //System.out.println("Total Count " + rd.getTotalColumnCount()); + String reportTitle = (nvl(rr.getReportTitle()).length()>0?rr.getReportTitle():rr.getReportName()); + String reportDescr = rr.getReportDescr(); + + col = getColumnCountForDownloadFile(rr,rd); + /*if (!rd.reportRowHeaderCols.hasNext()) + col = rd.getTotalColumnCount(); + else + col = rd.getTotalColumnCount(); + */ + int rowNum = 0; + HSSFSheet sheet = wb.createSheet(getSheetName()); + sheet.getPrintSetup().setLandscape(true); + + if (Globals.getPrintTitleInDownload()&& reportTitle != null ) { + paintExcelHeader(wb, rowNum, col, reportTitle, reportDescr, sheet); + rowNum = sheet.getLastRowNum(); + } else + rowNum = 0; + if (Globals.getPrintParamsInDownload() && rr.getParamNameValuePairsforPDFExcel(request, 1) != null) { + ArrayList paramsList = rr.getParamNameValuePairsforPDFExcel(request, 1); + if(paramsList.size()<=0) { + paramsList = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + } + + paintExcelParams(wb,rowNum,col,paramsList, rr.getFormFieldComments(request), sheet, reportTitle, reportDescr); + } // if + rowNum = sheet.getLastRowNum(); + + String formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); + formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + response.reset(); + response.setContentType("application/vnd.ms-excel"); + response.setHeader("Content-disposition", "attachment;filename="+formattedReportName+formattedDate+user_id+".xls"); + sos = response.getOutputStream(); + + if(type == 3 && rr.getSemaphoreList()==null && !(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) ) { //type = 3 is whole + //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + //String sql_whole = rr.getWholeSQL(); + String sql_whole = ""; + sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + if(sql_whole==null) { + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) + sql_whole = rr.getWholeSQL(); + else + sql_whole = rr.getReportSQL(); + } + + returnValue = paintExcelData(wb, rowNum, col, rd, styles,rr, sheet, sql_whole, sos, request); + } else if(type == 2) { + returnValue = paintExcelData(wb, rowNum, col, rd, styles,rr, sheet, "", sos, request); + } else { + //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + String action = request.getParameter(AppConstants.RI_ACTION); + if(!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session")) { + rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, false /*download*/); + } + if(rr.getSemaphoreList()!=null) { + if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + returnValue = paintExcelData(wb, rowNum, col, rd, styles,rr, sheet, "", sos, request); + } else { + rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, true); + returnValue = paintExcelData(wb, rowNum, col, rd, styles,rr, sheet, "", sos, request); + } + } else { + String sql_whole = ""; + sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + if(sql_whole==null) { + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) + sql_whole = rr.getWholeSQL(); + else + sql_whole = rr.getReportSQL(); + } + + returnValue = paintExcelData(wb, rowNum, col, rd, styles,rr, sheet, sql_whole, sos, request); + } + } + if( returnValue == 0 ) { + if (Globals.getPrintFooterInDownload()) { + rowNum = sheet.getLastRowNum(); + rowNum += 2; + paintExcelFooter(wb, rowNum, col, sheet); + } + //Alternatively: + wb.setPrintArea( + 0, //sheet index + 0, //start column + col, //end column + 0, //start row + rowNum //end row + ); + //TODO Remove comment + wb.write(sos); + sos.flush(); + sos.close(); + wb = null; + } else { + //sos.flush(); + //sos.close(); +/* response.reset(); + + RequestDispatcher dispatcher = request.getRequestDispatcher("/raptor.htm?action=raptor&r_action=report.message"); + request.setAttribute("message", Globals.getUserDefinedMessageForMemoryLimitReached()); + try { + dispatcher.forward(request, response); + } catch (ServletException ex) {} +*/ + } + } + } + + + public void createFlatFileContent(Writer out, ReportData rd, ReportRuntime rr, + HttpServletRequest request, HttpServletResponse response, String user_id) + throws IOException, Exception { + ReportHandler rephandler = new ReportHandler(); + String reportID = rr.getReportID(); + rr = rephandler.loadReportRuntime(request, reportID); + String query = rr.getWholeSQL(); + String dbInfo = rr.getDbInfo(); + //File f = new File(request.(arg0)("/")); + DataSet ds = ConnectionUtils.getDataSet(query, dbInfo); + + //Writing Column names to the file + List l = rr.getAllColumns(); + StringBuffer allColumnsBuffer = new StringBuffer(); + DataColumnType dct = null; + + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + allColumnsBuffer.append(dct.getDisplayName()); + if(iter.hasNext()) + allColumnsBuffer.append("|"); + } + rd = rr.loadReportData(-1, user_id, -1,request, true); + //PrintWriter txtOut = new PrintWriter(out); + //response.setContentType("application/notepad"); + //response.setHeader("Content-disposition", "attachment;filename=download_all_"+AppUtils.getUserID(request)+".txt"); + ServletOutputStream sos = response.getOutputStream(); + + //No Report Title for flat file. +// if (Globals.getPrintTitleInDownload() && reportTitle != null) { +// txtOut.println(); +// txtOut.println("\"" + reportTitle + "\""); +// txtOut.println(); +// if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { +// txtOut.println("\"" + reportDescr + "\""); +// txtOut.println(); +// } +// } // if + // No Params either +// int count = 0; +// if (Globals.getPrintParamsInDownload() && reportParamNameValues != null) { +// for (Iterator iter = reportParamNameValues.iterator(); iter.hasNext();) { +// count += 1; +// if(count == 1) txtOut.println(); +// IdNameValue value = (IdNameValue) iter.next(); +// txtOut.println(value.getId() + " = " + value.getName()); +// if(!iter.hasNext()) txtOut.println(); +// } // for +// } // if + + + + boolean firstPass = true; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + DataRow dr = rd.reportDataRows.getNext(); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + + sos.print(rh.getRowTitle()); + if(rhc.hasNext()) sos.print("|"); + } // for + firstPass = false; + + for (dr.resetNext(); dr.hasNext();) { + DataValue dv = dr.getNext(); + + sos.print( dv.getDisplayValue()); + if(dr.hasNext()) sos.print("|"); + } // for + + sos.println(); + } // for + //sos.flush(); + sos.close(); + } // createFlatFileContent + + + public void createExcel2007FileContent(Writer out, ReportData rd, ReportRuntime rr, HttpServletRequest request, + HttpServletResponse response, String user_id, int type) + throws Exception { + + // to check performance + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + + logger.debug(EELFLoggerDelegate.debugLogger, ("STARTING.EXCELX DOWNLOAD....")); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.totalMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### END #####")); + + // Adding utility for downloading Dashboard reports. + + Map styles = new HashMap(); + HttpSession session = request.getSession(); + ServletOutputStream sos = null; + BufferedInputStream buf = null; + XSSFWorkbook wb = null; + String formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); + String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + //Sheet name to be filled is taken from property. How would this be called if it is Dashboard? + //commented out since application will create and leave it blank. + //setSheetName(Globals.getSheetName()); + boolean isDashboard = false; + if ((session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) { + isDashboard = true; + } + //boolean isDashboard = (session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null); + ArrayList sheetArrayList = new ArrayList(); + + Map reportRuntimeMap = null; + Map reportDataMap = null; + + ArrayList reportIDList = new ArrayList(); + + //Map reportDisplayTypeMap = null; + if(isDashboard) { + reportRuntimeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + reportDataMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + + if(reportRuntimeMap!=null) { + Set setReportRuntime = reportRuntimeMap.entrySet(); + for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + reportIDList.add(rrDashRep.getReportID()); + } + } + } + + + + + int col = 0; + String reportTitle = (nvl(rr.getReportTitle()).length()>0?rr.getReportTitle():rr.getReportName()); + String reportDescr = rr.getReportDescr(); + + // Total Columns visible in excel + //col = getColumnCountForDownloadFile(rr, rd); + + int rowNum = 0; + + + XSSFSheet sheet = null; + //save the template + String filename = ""; + String extension = ""; + + String sheetRef = null; + + FileOutputStream os = null; //template file + File templateFile = null; + + if(isDashboard) { + if(reportRuntimeMap!=null) { + + FileInputStream readTemplate = null; + //Load customized styles + int count = 0; + + //If template supplied by Application + String templateFilename = rr.getTemplateFile(); + extension = templateFilename.substring(templateFilename.lastIndexOf(".")+1); + filename = formattedReportName+formattedDate+user_id; + + Set setReportRuntimeWB = reportRuntimeMap.entrySet(); + for(Iterator iter = setReportRuntimeWB.iterator(); iter.hasNext(); ) { + count++; + Map.Entry entry = (Entry) iter.next(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + os = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); + + if(count==1) { + if(nvl(rr.getTemplateFile()).length()>0) { + readTemplate = new FileInputStream(org.openecomp.portalsdk.analytics.system.AppUtils.getExcelTemplatePath()+rr.getTemplateFile()); + wb=new XSSFWorkbook(readTemplate); + } else { + //copy the os file to new file and open new file in below line + wb=new XSSFWorkbook(); + } + } else { + readTemplate = new FileInputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); + wb=new XSSFWorkbook(readTemplate); + } + if(rrDashRep!=null) + styles = loadXSSFStyles(rrDashRep, wb, styles); + String reportSheetName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); + if(nvl(reportSheetName).length()>28) + reportSheetName = reportSheetName.substring(0, 28); + sheet = wb.createSheet(count+"-"+reportSheetName); + if(!Globals.printExcelInLandscapeMode()) + sheet.getPrintSetup().setLandscape(false); + else + sheet.getPrintSetup().setLandscape(true); + wb.write(os); + os.flush(); + if(nvl(rr.getTemplateFile()).length()>0) { + readTemplate.close(); + } + os.close(); + + FileInputStream inF = new FileInputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); + FileOutputStream outStream = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); + copyStream(inF, outStream); + outStream.flush(); + outStream.close(); + inF.close(); + + } + + FileInputStream xlsIn = null; + POIFSFileSystem fileSystem = null; + buf = null; + FileOutputStream xlsOut = null; + formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + String xlsFName = "dashboard"+formattedDate+user_id+".xls"; + + Set setReportRuntime = reportRuntimeMap.entrySet(); + Set setReportDataMap = reportDataMap.entrySet(); + Iterator iter2 = setReportDataMap.iterator(); + + + //filename = templateFilename.substring(0, templateFilename.lastIndexOf("."))+"_"+formattedDate+user_id; + + count = 0; + for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { + count++; + + Map.Entry entry = (Entry) iter.next(); + Map.Entry entryData = (Entry) iter2.next(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + ReportData rdDashRep = (ReportData) entryData.getValue(); + + String reportSheetName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); + if(nvl(reportSheetName).length()>28) + reportSheetName = reportSheetName.substring(0, 28); + sheet = wb.getSheet(count+"-"+reportSheetName); + sheetRef = sheet.getPackagePart().getPartName().getName(); + + //Step 2. Generate XML file. + File tmp = File.createTempFile("sheet", ".xml"); + FileOutputStream fileOutTemp = new FileOutputStream(tmp); + Writer fw = new OutputStreamWriter(fileOutTemp, XML_ENCODING); + String sql_whole = rrDashRep.getWholeSQL(); + + SpreadsheetWriter sw = new SpreadsheetWriter(fw); + sw.beginSheet(); + + + generate(wb, sw, styles, rdDashRep, sql_whole, rrDashRep, request, sheet); + + + sw.endSheet(); + + fw.flush(); + fw.close(); + fileOutTemp.flush(); + fileOutTemp.close(); + + + //Step 3. Substitute the template entry with the generated data + + FileOutputStream outF = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); + templateFile = new File(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); + substitute(templateFile, tmp, sheetRef.substring(1), outF); + outF.flush(); + outF.close(); + + FileInputStream inF = new FileInputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); + FileOutputStream outStream = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); + copyStream(inF, outStream); + outStream.flush(); + outStream.close(); + inF.close(); + } + } + } else { + //If template supplied by Application + if(nvl(rr.getTemplateFile()).length()>0) { + String templateFilename = rr.getTemplateFile(); + extension = templateFilename.substring(templateFilename.lastIndexOf(".")+1); + filename = formattedReportName+formattedDate+user_id; + //filename = templateFilename.substring(0, templateFilename.lastIndexOf("."))+"_"+formattedDate+user_id; + } else + filename = formattedReportName+formattedDate+user_id; + + + if(nvl(rr.getTemplateFile()).length()<=0) { + os = new FileOutputStream(AppUtils.getTempFolderPath()+"template"+formattedDate+user_id+".xlsx"); + wb=new XSSFWorkbook(); + //Load customized styles + if (rr != null) + styles = loadXSSFStyles(rr, wb, styles); + //create data sheet + if(isDashboard) { + + } else { + + } + String reportSheetName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); + if(nvl(reportSheetName).length()>28) + reportSheetName = reportSheetName.substring(0, 28); + sheet = wb.createSheet(reportSheetName); + + //customized mode + if(!Globals.printExcelInLandscapeMode()) + sheet.getPrintSetup().setLandscape(false); + else + sheet.getPrintSetup().setLandscape(true); + //get data sheet name + sheetRef = sheet.getPackagePart().getPartName().getName(); + wb.write(os); + os.flush(); + //wb = null; + os.close(); + + } else { + os = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); + FileInputStream readTemplate = new FileInputStream(org.openecomp.portalsdk.analytics.system.AppUtils.getExcelTemplatePath()+rr.getTemplateFile()); + wb=new XSSFWorkbook(readTemplate); + if (rr != null) + styles = loadXSSFStyles(rr, wb, styles); + sheet = wb.getSheetAt(0); + if(!Globals.printExcelInLandscapeMode()) + sheet.getPrintSetup().setLandscape(false); + else + sheet.getPrintSetup().setLandscape(true); + //sheet = wb.getSheet(getSheetName()); + sheetRef = sheet.getPackagePart().getPartName().getName(); + wb.write(os); + os.flush(); + readTemplate.close(); + //wb = null; + os.close(); + } + + //Step 2. Generate XML file. + File tmp = File.createTempFile("sheet", ".xml"); + FileOutputStream fileOutTemp = new FileOutputStream(tmp); + Writer fw = new OutputStreamWriter(fileOutTemp, XML_ENCODING); + + //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + String sql_whole = ""; + sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + if(sql_whole==null) { + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) + sql_whole = rr.getWholeSQL(); + else + sql_whole = rr.getReportSQL(); + } + + SpreadsheetWriter sw = new SpreadsheetWriter(fw); + + sw.beginSheet(); + + if((rd.getDataRowCount() >= rr.getReportDataSize()) && !rr.getReportType().equals(AppConstants.RT_HIVE)) { + sql_whole=""; + } + + generate(wb, sw, styles, rd, sql_whole, rr, request, sheet); + + sw.endSheet(); + + fw.flush(); + fw.close(); + fileOutTemp.flush(); + fileOutTemp.close(); + + + //Step 3. Substitute the template entry with the generated data + + FileOutputStream outF = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); + + if(nvl(rr.getTemplateFile()).length()>0) { + templateFile = new File(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); + } else + templateFile = new File(AppUtils.getTempFolderPath()+"template"+formattedDate+user_id+".xlsx"); + + substitute(templateFile, tmp, sheetRef.substring(1), outF); + outF.flush(); + outF.close(); + + } + //get servlet output stream + + + response.reset(); + sos = response.getOutputStream(); + String mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + if(extension.equals("xlsm")) + mime_type = "application/vnd.ms-excel.sheet.macroEnabled.12"; + response.setContentType(mime_type); + + response.setHeader("Content-disposition", "attachment;filename="+filename+"."+ nvls(extension, "xlsx")); + + buf = new BufferedInputStream(new FileInputStream(AppUtils.getTempFolderPath()+filename + "."+ nvls(extension, "xlsx"))); + int readBytes = 0; + + //read from the file; write to the ServletOutputStream + while ((readBytes = buf.read()) != -1) + sos.write(readBytes); + + buf.close(); + sos.flush(); + sos.close(); + logger.debug(EELFLoggerDelegate.debugLogger, ("ENDING..DOWNLOADING XLSX...")); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.totalMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### END #####")); + } + + /** + * + * @param zipfile the template file + * @param tmpfile the XML file with the sheet data + * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml + * @param out the stream to write the result to + */ + private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException { + ZipFile zip = new ZipFile(zipfile); + + ZipOutputStream zos = new ZipOutputStream(out); + + @SuppressWarnings("unchecked") + Enumeration en = (Enumeration) zip.entries(); + while (en.hasMoreElements()) { + ZipEntry ze = en.nextElement(); + if(!ze.getName().equals(entry)){ + zos.putNextEntry(new ZipEntry(ze.getName())); + InputStream is = zip.getInputStream(ze); + copyStream(is, zos); + is.close(); + } + } + zos.putNextEntry(new ZipEntry(entry)); + InputStream is = new FileInputStream(tmpfile); + copyStream(is, zos); + zos.flush(); + zos.close(); + is.close(); + zip.close(); + } + + private static void copyStream(InputStream in, OutputStream out) throws IOException { + byte[] chunk = new byte[1024]; + int count; + while ((count = in.read(chunk)) >=0 ) { + out.write(chunk,0,count); + } + } + + + public void createCSVFileContent(Writer out, ReportData rd, + ReportRuntime rr, HttpServletRequest request, HttpServletResponse response) + throws RaptorException { + //ArrayList reportParamNameValues = rr.getParamNameValuePairs(); + //String reportTitle = rr.getReportName(); + //String reportDescr = rr.getReportDescr(); + PrintWriter csvOut = new PrintWriter(out); + ServletOutputStream sos = null; + BufferedInputStream buf = null; + String fileName = ""; + String formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); + String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + String fName = formattedReportName+formattedDate+AppUtils.getUserID(request); + boolean raw = AppUtils.getRequestFlag(request, "raw"); + String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + + String csvFName = fName+".csv"; + String zipFName = fName+".zip"; + if(true) { + try { + fileName = AppUtils.getTempFolderPath()+""+csvFName; + csvOut = new PrintWriter(new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(fileName), "UTF-8")), false); + } catch (FileNotFoundException fex) { + fex.printStackTrace(); + } + catch (UnsupportedEncodingException fex1) { + fex1.printStackTrace(); + } + } + HtmlStripper strip = new HtmlStripper(); + ResultSet rs = null; + //OracleConnection conn = null; + //OracleStatement st = null; + //Connection conO = null; + //Statement stO = null; + Connection conn = null; + Statement st = null; + ResultSetMetaData rsmd = null; + ColumnHeaderRow chr = null; + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + String valueName = ""; + if(!raw) { + String reportTitle = (nvl(rr.getReportTitle()).length()>0?rr.getReportTitle():rr.getReportName()); + csvOut.println(); + csvOut.print("\"" + reportTitle + "\","); + csvOut.println(); + + if(Globals.disclaimerPositionedTopInCSVExcel()) { + if(Globals.getShowDisclaimer()) { + csvOut.println(); + csvOut.print("\"" + Globals.getFooterFirstLine() + "\","); + csvOut.println(); + csvOut.print("\"" + Globals.getFooterSecondLine() + "\","); + csvOut.println(); + csvOut.println(); + } + } + } + if (Globals.getPrintParamsInCSVDownload() && !raw) { + ArrayList paramsList = rr.getParamNameValuePairsforPDFExcel(request, 1); + if(paramsList.size()<=0) { + paramsList = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + } + int paramSeq = 0; + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + //System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); + if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if(paramSeq <= 1) { + csvOut.print("\"" + "Run-time Parameters" + "\""); + csvOut.println(); + //strBuf.append("Run-time Parameters\n"); + } + csvOut.print("\"" + value.getId() +":" + "\","); + valueName = nvl(value.getName()); + if(valueName.indexOf("~")!= -1 && valueName.startsWith("(")) { + csvOut.print("\"'" + valueName.replaceAll("~",",")+ "'\","); + } else { + if(valueName.startsWith("(") && valueName.endsWith(")")) { + csvOut.print("\"" + valueName.replaceAll("~",",").substring(1, valueName.length()-1)+ "\","); + } else + csvOut.print("\"" + valueName.replaceAll("~",",")+ "\","); + } + csvOut.println(); + + //strBuf.append(value.getId()+": "+ value.getName()+"\n"); + } + } //for + csvOut.println(); + csvOut.println(); + } + + System.out.println("##### Heap utilization statistics [MB] #####"); + System.out.println("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb); + System.out.println("Free Memory:" + + runtime.freeMemory() / mb); + System.out.println("Total Memory:" + runtime.totalMemory() / mb); + System.out.println("Max Memory:" + runtime.maxMemory() / mb); + + sql_whole = ""; + sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + if(sql_whole==null) { + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) + sql_whole = rr.getWholeSQL(); + else + sql_whole = rr.getReportSQL(); + } + + + if(nvl(sql_whole).length()>0) { + try { + conn = ConnectionUtils.getConnection(rr.getDbInfo()); + st = conn.createStatement(); + //conn.setDefaultRowPrefetch(1000); + //st.setFetchDirection(ResultSet.TYPE_FORWARD_ONLY); + //st.setFetchSize(1000); + System.out.println("************* Map Whole SQL *************"); + System.out.println(sql_whole); + System.out.println("*****************************************"); + rs = st.executeQuery(sql_whole); + //st.setFetchSize(1000); + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + String title = ""; + + if(rd!=null) { + + /*if(rd.reportTotalRowHeaderCols!=null) { + csvOut.print("\"" + "#" + "\","); + }*/ + + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + chr = rd.reportColumnHeaderRows.getNext(); + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + title = ch.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + if(ch.isVisible() && nvl(title).length()>0) { + csvOut.print("\"" + title + "\","); + for (int i = 1; i < ch.getColSpan(); i++) + csvOut.print(","); + } + } // for + + csvOut.println(); + } // for + int rowCount = 0; + while(rs.next()) { +/* if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { + csvOut.print(Globals.getUserDefinedMessageForMemoryLimitReached() + " " + rowCount +"records out of " + rr.getReportDataSize() + " were downloaded to CSV."); + break; + } +*/ rowCount++; + //if(!raw) { + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i)); + } + /*if(rd.reportDataTotalRow!=null) { + csvOut.print("\"" + rowCount + "\","); + }*/ + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + title = ch.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + + if(ch.isVisible() && nvl(title).length()>0) { + csvOut.print("\"" + strip.stripCSVHtml(nvl((String)colHash.get(ch.getColId().toUpperCase()))) + "\","); + } + + } + csvOut.println(); + /*} else { + for (int i = 1; i <= numberOfColumns; i++) { + csvOut.print("\"" + strip.stripCSVHtml( rs.getString(i)) + "\","); + } + csvOut.println(); + }*/ + + } + + if(rd.reportDataTotalRow!=null) { + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { + DataRow dr = rd.reportDataTotalRow.getNext(); + csvOut.print("\"" + "Total" + "\","); + dr.resetNext();dr.getNext(); + for (; dr.hasNext();) { + DataValue dv = dr.getNext(); + if(dv.isVisible()) { + csvOut.print("\"" + strip.stripCSVHtml(dv.getDisplayValue()) + "\","); + } + } // for + + csvOut.println(); + } + } + + if(rowCount == 0) { + csvOut.print("\"No Data Found \""); + } + } else { + csvOut.print("\"No Data Found \""); + } + + } catch (SQLException ex) { + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + throw new RaptorException (ex); + } finally { + try { + if(conn!=null) + conn.close(); + if(st!=null) + st.close(); + if(rs!=null) + rs.close(); + } catch (SQLException ex) { + throw new RaptorException(ex); + } + } + + if(!raw) { + if(!Globals.disclaimerPositionedTopInCSVExcel()) { + if(Globals.getShowDisclaimer()) { + csvOut.print("\"" + Globals.getFooterFirstLine() + "\","); + csvOut.println(); + csvOut.print("\"" + Globals.getFooterSecondLine() + "\","); + csvOut.println(); + } + } + } + + // csvOut.flush(); + } else { + boolean firstPass = true; + if(rd!=null) { + if(rd.reportTotalRowHeaderCols!=null) { + csvOut.print("\"" + "#" + "\","); + } + + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + chr = rd.reportColumnHeaderRows.getNext(); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + + if (firstPass) + csvOut.print("\"" + rhc.getColumnTitle() + "\""); + csvOut.print(","); + } // for + firstPass = false; + + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + csvOut.print("\"" + ch.getColumnTitle() + "\","); + for (int i = 1; i < ch.getColSpan(); i++) + csvOut.print(","); + } + } // for + + csvOut.println(); + } // for + + firstPass = true; + int rowCount = 0; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + if(rd.reportDataTotalRow!=null) { + rowCount++; + csvOut.print("\"" + rowCount + "\","); + } + + DataRow dr = rd.reportDataRows.getNext(); + + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + + csvOut.print("\"" + strip.stripCSVHtml(rh.getRowTitle()) + "\","); + } // for + firstPass = false; + + for (dr.resetNext(); dr.hasNext();) { + DataValue dv = dr.getNext(); + if(dv.isVisible()) + csvOut.print("\"" + strip.stripCSVHtml(dv.getDisplayValue()) + "\","); + } // for + + csvOut.println(); + } // for + if(rd.reportDataTotalRow!=null) { + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { + DataRow dr = rd.reportDataTotalRow.getNext(); + csvOut.print("\"" + "Total" + "\","); + firstPass = false; + + for (dr.resetNext(); dr.hasNext();) { + DataValue dv = dr.getNext(); + if(dv.isVisible()) + csvOut.print("\"" + strip.stripCSVHtml(dv.getDisplayValue()) + "\","); + } // for + + csvOut.println(); + } + } + + if(!raw) { + if(!Globals.disclaimerPositionedTopInCSVExcel()) { + if(Globals.getShowDisclaimer()) { + csvOut.print("\"" + Globals.getFooterFirstLine() + "\","); + csvOut.println(); + csvOut.print("\"" + Globals.getFooterSecondLine() + "\","); + csvOut.println(); + } + } + } + + //csvOut.flush(); + } else { + csvOut.print("\"No Data Found \""); + } + } + csvOut.flush(); + csvOut.close(); + +/* + if (Globals.getPrintTitleInDownload() && reportTitle != null) { + csvOut.println(); + csvOut.println("\"" + reportTitle + "\""); + csvOut.println(); + if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { + csvOut.println("\"" + reportDescr + "\""); + csvOut.println(); + } + } // if + + if (Globals.getPrintParamsInDownload() && reportParamNameValues != null) { + csvOut.println(); + for (Iterator iter = reportParamNameValues.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + csvOut.println("\"" + value.getId() + " = " + value.getName() + "\""); + } // for + csvOut.println(); + } // if +*/ + if(true && !raw) { + try { + + //final int BUFFER = 2048; + + //fis.read(buf,0,buf.length); + int size = 0; + byte[] buffer = new byte[1024]; + + //CRC32 crc = new CRC32(); + //PrintStream fos = new PrintStream(new WriterOutputStream(out)); + //BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); + //ZipOutputStream s = new ZipOutputStream(dest); + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(AppUtils.getTempFolderPath()+""+zipFName)); + FileInputStream fis = new FileInputStream(fileName); + + //s.setLevel(6); + + ZipEntry entry = new ZipEntry(csvFName); + //crc.reset(); + zos.putNextEntry(entry); + + // read data to the end of the source file and write it to the zip + // output stream. + while ((size = fis.read(buffer, 0, buffer.length)) > 0) { + zos.write(buffer, 0, size); + } + + zos.closeEntry(); + fis.close(); + + // Finish zip process + zos.close(); + + } catch(Exception e) { + e.printStackTrace(); + } + } + + response.reset(); + java.io.File file = null; + + if(true && !raw) { + response.setContentType("application/octet-stream"); + response.setHeader("Content-disposition","attachment;filename="+fName+".zip"); + file = new java.io.File(AppUtils.getTempFolderPath()+""+fName+".zip"); + } else { + response.setContentType("application/csv"); + response.setHeader("Content-disposition","attachment;filename="+fName+".csv"); + file = new java.io.File(AppUtils.getTempFolderPath()+""+fName+".csv"); + } + + + FileInputStream fileIn = null; + int c; + try { + sos = response.getOutputStream(); + fileIn = new FileInputStream(file); + buf = new BufferedInputStream(fileIn); + byte [] bOut = new byte [4096]; + //read from the file; write to the ServletOutputStream + //while ((readBytes = buf.read()) != -1) + int readBytes = 0; + while ((readBytes = buf.read (bOut, 0, 4096))> 0) { + buf.available(); + sos.write (bOut, 0, readBytes); + } + + } catch (IOException ex) { + ex.printStackTrace(); + } + catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if (sos != null) + sos.close(); + if (buf != null) + buf.close(); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + + File f = new File (AppUtils.getTempFolderPath() + + fName); + if(f.exists()) f.delete(); + System.out.println("##### Heap utilization statistics [MB] #####"); + System.out.println("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + + } // createCSVFileContent + +/* public String saveCSVPageFile(HttpServletRequest request, ReportData rd, + ArrayList reportParamNameValues, String reportTitle, String reportDescr) { + try { + String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportTitle); + String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + + String csvFName = formattedReportName+formattedDate+AppUtils.getUserID(request)+".csv"; + //String csvFName = AppUtils.generateFileName(request, AppConstants.FT_CSV); + + BufferedWriter csvOut = new BufferedWriter(new FileWriter(AppUtils + .getTempFolderPath() + + csvFName)); + createCSVFileContent(csvOut, rd, reportParamNameValues, reportTitle, reportDescr); + csvOut.close(); + + return csvFName; + } catch (Exception e) { + (new ErrorHandler()).processError(request, "Exception saving data to CSV file: " + + e.getMessage()); + return null; + } + } // saveCSVPageFile +*/ + +// public String saveAsFlatFile(HttpServletRequest request, ReportData rd, +// ReportRuntime rr, String reportTitle, String reportDescr) { +// try { +// String csvFName = AppUtils.generateFileName(request, AppConstants.FT_TXT); +// +// BufferedWriter txtOut = new BufferedWriter(new FileWriter(AppUtils +// .getTempFolderPath() +// + csvFName)); +// createFlatFileContent(txtOut, rd, rr, reportTitle, reportDescr); +// txtOut.close(); +// +// return csvFName; +// } catch (Exception e) { +// (new ErrorHandler()).processError(request, "Exception saving data to CSV file: " +// + e.getMessage()); +// return null; +// } +// } // saveCSVPageFile + + public String saveXMLFile(HttpServletRequest request, String reportName, String reportXML) { + try { + String xmlFName = AppUtils.generateUniqueFileName(request, reportName, AppConstants.FT_XML); + + PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File( + AppUtils.getTempFolderPath() + xmlFName)))); + xmlOut.println(reportXML); + xmlOut.close(); + + //return AppUtils.getTempFolderURL() + // + java.net.URLEncoder.encode(java.net.URLDecoder.decode(xmlFName)); + return java.net.URLEncoder.encode(java.net.URLDecoder.decode(xmlFName)); + + } catch (Exception e) { + (new ErrorHandler()).processError(request, + "Exception saving XML source to file system: " + e.getMessage()); + return null; + } + } // saveXMLFile + + public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID) + throws RaptorException { + return loadReportRuntime(request, reportID, true); + } // loadReportRuntime + + public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID, + boolean prepareForExecution) throws RaptorException { + return loadReportRuntime(request, reportID, true, 2); // where 2 is adding to session + } + public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID, + boolean prepareForExecution, int requestFlag) throws RaptorException { + boolean refresh = nvl(request.getParameter(AppConstants.RI_REFRESH)).toUpperCase().startsWith("Y"); + boolean rDisplayContent = AppUtils.getRequestFlag(request, + AppConstants.RI_DISPLAY_CONTENT) + || AppUtils.getRequestFlag(request, "noFormFields"); + + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + boolean inSchedule = AppUtils.getRequestFlag(request, AppConstants.SCHEDULE_ACTION); + if (rr != null ) { + if(requestFlag == 7) { // DASH + String reportXML = ReportLoader.loadCustomReportXML(reportID); + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); + rr = ReportRuntime.unmarshal(reportXML, reportID, request); + rr.setParamValues(request, false,refresh); + rr.setDisplayFlags(true, true); // show content even at the first time + return rr; + } else { + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Load Report Runtime "+ reportID + " " +rr.getReportID() + " " + request.getParameter("refresh") )); + if (reportID.equals(rr.getReportID()) && (request.getParameter("refresh")==null || !request.getParameter("refresh").equals("Y"))) { + // The report runtime is already in the session + if (prepareForExecution) { + boolean resetParams = AppUtils.getRequestFlag(request, + AppConstants.RI_RESET_PARAMS); + rr.setParamValues(request, resetParams,refresh); + + if (resetParams) + rr.resetVisualSettings(); + rr.setDisplayFlags(nvl(request.getParameter(AppConstants.RI_SOURCE_PAGE)) + .length() == 0, rDisplayContent || rr.isDisplayOptionHideForm()); + } // if + + return rr; + } // if + } + } + + /* + * Cannot convert the definition => XML file not saved for preview also, + * commented code not maintained up to date ReportDefinition rdef = + * (ReportDefinition) + * request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); + * if(rdef!=null) if(reportID.equals(rdef.getReportID())) { // The + * report definition is in the session => create report runtime from it + * rr = new ReportRuntime(rdef, request); if(prepareForExecution) { + * request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, + * rr); + * rr.setDisplayFlags(request.getParameter(AppConstants.RI_SOURCE_PAGE)==null); } // + * if return rr; } // if + */ + + // Report is NOT in the session => load from the database + String reportXML = ReportLoader.loadCustomReportXML(reportID); + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); + + rr = ReportRuntime.unmarshal(reportXML, reportID, request); + if (prepareForExecution) { + String userID ; + int flag = 0; + if(request.getAttribute("schedule_email_userId") != null) { + userID = (String)request.getAttribute("schedule_email_userId"); + flag = 1; + } + else + userID = AppUtils.getUserID(request); + // If it is dashboard type then report can be viewed without specific privilege to report + String dashboardId = AppUtils.getRequestValue(request, AppConstants.RI_DASHBOARD_ID); + //System.out.println("USSSSSSSSSSSSERID " + userID); + //System.out.println("PDF " + AppUtils.getRequestNvlValue(request, "pdfAttachmentKey") ); + if(!rr.isDashboardType() && !(isReportAddedAsDashboard(request, dashboardId, rr.getReportID()))) { + if ( AppUtils.getRequestNvlValue(request, "pdfAttachmentKey").length()<=0 ) + if(flag == 1 )rr.checkUserReadAccess(request, userID); + else rr.checkUserReadAccess(request); + } + // TODO ON Demand + //rr.setXmlFileName(saveXMLFile(request, rr.getReportName(), reportXML)); + if (rDisplayContent) { + //System.out.println("In rDisplayContent "); + rr.setParamValues(request, false,true); + //if (requestFlag==2) + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + } + if(inSchedule) { + //System.out.println("In inSchedule "); + rr.setParamValues(request, false,false); + } + if( requestFlag == 7 ) { // DASH + rr.setDisplayFlags(true, true); + } else { + rr.setDisplayFlags(request.getParameter(AppConstants.RI_SOURCE_PAGE) == null, + rDisplayContent || rr.isDisplayOptionHideForm()); + } +// System.out.println("Report ID B4 Id in reportHandler " +// + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); +// System.out.println("requestFlag " + requestFlag); + if(requestFlag==2 && !rDisplayContent) { + //System.out.println("In Request Flag "); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + rr.setParamValues(request, false, false); + } + else if(requestFlag==1) { + rr.setParamValues(request, false,refresh); + request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + + } +// System.out.println("Report ID B4 Id in reportHandler " +// + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); + //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + } // if + + return rr; + } // loadReportRuntime + + private boolean isReportAddedAsDashboard(HttpServletRequest request, String dashboardId, String reportId)throws RaptorException { + if(nvl(dashboardId).length() <= 0) + return false; + String reportXML = ReportLoader.loadCustomReportXML(dashboardId); + ReportDefinition rdef = createReportDefinition(request, dashboardId, reportXML); + List l = rdef.getDashBoardReports().getReportsList(); + for (Iterator iterator = l.iterator(); iterator.hasNext();) { + Reports reports = (Reports) iterator.next(); + if(reports.getReportId().equals(reportId)) return true; + + } + return false; + } + + public ReportDefinition createReportDefinition(HttpServletRequest request, + String reportID, String reportXML) throws RaptorException { + ReportDefinition rdef = ReportDefinition.unmarshal(reportXML, reportID, request); + rdef.generateWizardSequence(request); + return rdef; + } // createReportDefinition + + public ReportDefinition loadReportDefinition(HttpServletRequest request, String reportID) + throws RaptorException { + //System.out.println("********* ReportID " + reportID); + boolean isReportIDBlank = (reportID.length() == 0 || reportID.equals("-1")); + String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), ""); + String wizardActionKey = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION), ""); + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + if(nvl(actionKey).equals("report.edit")) + rdef = null; + //ReportDefinition rdef = null; + if (rdef != null) + if (isReportIDBlank || reportID.equals(rdef.getReportID())) { + // The report definition is already in the session + return rdef; + } + + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + if (rr != null) + if (isReportIDBlank || reportID.equals(rr.getReportID())) { + // The report runtime is in the session => create report + // definition from it + rdef = new ReportDefinition(rr, request); + String userID = AppUtils.getUserID(request); + rdef.generateWizardSequence(request); + // rdef.checkUserWriteAccess(userID); + + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + return rdef; + } // if + + // Report is NOT in the session => load from the database + if (isReportIDBlank) + rdef = ReportDefinition.createBlank(request); + else { + String reportXML = ReportLoader.loadCustomReportXML(reportID); + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); + rdef = createReportDefinition(request, reportID, reportXML); + } // else + + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + return rdef; + } // loadReportDefinition + + public void setSheetName( String sheet_name ) { + SHEET_NAME = sheet_name; + } + + public String getSheetName() { + return SHEET_NAME; + } + + /** + * Writes spreadsheet data in a Writer. + * (YK: in future it may evolve in a full-featured API for streaming data in Excel) + */ + public static class SpreadsheetWriter { + private final Writer _out; + private int _rownum; + + public SpreadsheetWriter(Writer out){ + _out = out; + } + + public void beginSheet() throws IOException { + _out.write("" + + "" ); + _out.write("\n"); + } + + public void endSheet() throws IOException { + _out.write(""); + _out.write(""); + } + + /** + * Insert a new row + * + * @param rownum 0-based row number + */ + public void insertRow(int rownum) throws IOException { + _out.write("\n"); + this._rownum = rownum; + } + + /** + * Insert row end marker + */ + public void endRow() throws IOException { + _out.write("\n"); + } + + public void createCell(int columnIndex, String value, int styleIndex) throws IOException { + String ref = new CellReference(_rownum, columnIndex).formatAsString(); + _out.write(""); + _out.write(""+value+""); + _out.write(""); + } + + public void createCell(int columnIndex, String value) throws IOException { + createCell(columnIndex, value, -1); + } + + public void createCell(int columnIndex, double value, int styleIndex) throws IOException { + String ref = new CellReference(_rownum, columnIndex).formatAsString(); + _out.write(""); + _out.write(""+value+""); + _out.write(""); + } + + public void createCell(int columnIndex, double value) throws IOException { + createCell(columnIndex, value, -1); + } + + public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException { + createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex); + } + } + + public int getColumnCountForDownloadFile(ReportRuntime rr, ReportData rd) { + int columnCount = 0; + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext(); + for(chr.resetNext(); chr.hasNext(); ) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + columnCount++; + } + } + } + if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if(rhc.isVisible()) { + columnCount++; + } + } + } + return columnCount; + } + + + private Map loadXSSFStyles(ReportRuntime rr, XSSFWorkbook wb, Map loadedStyles) { + XSSFCellStyle styleDefault = wb.createCellStyle(); + //System.out.println("Load Styles"); + // Style default will be normal with no background + XSSFFont fontDefault = wb.createFont(); + + XSSFDataFormat xssffmt = wb.createDataFormat(); + // The default will be plain . + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (font_size / 0.05)); + fontDefault.setFontName("Tahoma"); + + styleDefault.setAlignment(XSSFCellStyle.ALIGN_CENTER); + styleDefault.setBorderBottom(XSSFCellStyle.BORDER_THIN); + styleDefault.setBorderTop(XSSFCellStyle.BORDER_THIN); + styleDefault.setBorderLeft(XSSFCellStyle.BORDER_THIN); + styleDefault.setBorderRight(XSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDefault.setFillPattern(XSSFCellStyle.NO_FILL); + styleDefault.setFont(fontDefault); + ArrayList semColumnList = new ArrayList(); + List dsList = rr.getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType element = (DataSourceType) iter.next(); + List dcList = element.getDataColumnList().getDataColumn(); + for (Iterator iterator = dcList.iterator(); iterator.hasNext();) { + DataColumnType element1 = (DataColumnType) iterator.next(); + semColumnList.add(element1.getSemaphoreId()); + + } + } + SemaphoreList semList = rr.getSemaphoreList(); + Map hashMapStyles = new HashMap();; + Map hashMapFonts = new HashMap(); + hashMapFonts.put("default", fontDefault); + hashMapStyles.put("default", styleDefault); + XSSFCellStyle styleLeftDefault = wb.createCellStyle(); + styleLeftDefault.setAlignment(XSSFCellStyle.ALIGN_LEFT); + styleLeftDefault.setBorderBottom(XSSFCellStyle.BORDER_THIN); + styleLeftDefault.setBorderTop(XSSFCellStyle.BORDER_THIN); + styleLeftDefault.setBorderLeft(XSSFCellStyle.BORDER_THIN); + styleLeftDefault.setBorderRight(XSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleLeftDefault.setFillPattern(XSSFCellStyle.NO_FILL); + styleLeftDefault.setFont(fontDefault); + hashMapStyles.put("defaultLeft", styleLeftDefault); + + + XSSFCellStyle styleDate = wb.createCellStyle(); + styleDate.setAlignment(XSSFCellStyle.ALIGN_RIGHT); + styleDate.setDataFormat(xssffmt.getFormat("d-mmm-yy")); + styleDate.setAlignment(XSSFCellStyle.ALIGN_CENTER); + styleDate.setBorderBottom(XSSFCellStyle.BORDER_THIN); + styleDate.setBorderTop(XSSFCellStyle.BORDER_THIN); + styleDate.setBorderLeft(XSSFCellStyle.BORDER_THIN); + styleDate.setBorderRight(XSSFCellStyle.BORDER_THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDate.setFillPattern(XSSFCellStyle.NO_FILL); + styleDate.setFont(fontDefault); + hashMapStyles.put("date", styleDate); + + XSSFCellStyle rowHeaderStyle = wb.createCellStyle(); + XSSFFont headerFont = wb.createFont(); + headerFont.setBold(true); + rowHeaderStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + rowHeaderStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); + rowHeaderStyle.setFont(headerFont); + rowHeaderStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); + rowHeaderStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); + rowHeaderStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); + rowHeaderStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); + hashMapStyles.put("header", rowHeaderStyle); + + + XSSFCellStyle boldStyle = wb.createCellStyle(); + //headerFont = wb.createFont(); + //headerFont.setBold(true); + boldStyle.setFont(headerFont); + boldStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); + boldStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); + boldStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); + boldStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); + boldStyle.setAlignment(HorizontalAlignment.CENTER); + hashMapStyles.put("title", boldStyle); + + XSSFCellStyle cellStyle = null; + if (semList == null || semList.getSemaphore() == null) { + hashMapStyles.put("default", styleDefault); + } /*else { + for (Iterator iter = semList.getSemaphore().iterator(); iter.hasNext();) { + SemaphoreType sem = (SemaphoreType) iter.next(); + if(!semColumnList.contains(sem.getSemaphoreId())) continue; + //System.out.println("SemphoreId ----> " + sem.getSemaphoreId()); + FormatList fList = sem.getFormatList(); + List formatList = fList.getFormat(); + for (Iterator fIter = formatList.iterator(); fIter.hasNext();) { + FormatType fmt = (FormatType) fIter.next(); + if(fmt!=null){ + //if (fmt.getLessThanValue().length() > 0) { + cellStyle = wb.createCellStyle(); + XSSFFont cellFont = wb.createFont(); + //System.out.println("Format Id " + fmt.getFormatId()); + if (nvl(fmt.getBgColor()).length() > 0) { +// System.out.println("Load Styles " + +// fmt.getFormatId() +// + " " +fmt.getBgColor() + " " + +// ExcelColorDef.getExcelColor(fmt.getBgColor())); + cellStyle.setFillForegroundColor(ExcelColorDef.getExcelColor(fmt + .getBgColor())); + cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); + } + if (nvl(fmt.getFontColor()).length() > 0) { + cellFont.setColor(ExcelColorDef.getExcelColor(fmt.getFontColor())); + } else + cellFont.setColor((short) HSSFFont.COLOR_NORMAL); + if (fmt.isBold()) + cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + if (fmt.isItalic()) + cellFont.setItalic(true); + if (fmt.isUnderline()) + cellFont.setUnderline(HSSFFont.U_SINGLE); + if(nvl(fmt.getFontFace()).length()>0) + cellFont.setFontName(fmt.getFontFace()); + else + cellFont.setFontName("Tahoma"); + //cellFont.setFontHeight((short) (10 / 0.05)); + + if(nvl(fmt.getFontSize()).length()>0) { + try { + cellFont.setFontHeight((short) (Integer.parseInt(fmt.getFontSize()) / 0.05)); + } catch(NumberFormatException e){ + cellFont.setFontHeight((short) (font_size / 0.05)); + } + } + else + cellFont.setFontHeight((short) (font_size / 0.05)); + cellStyle.setFont(cellFont); + cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); + cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); + cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); + cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); + cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); + hashMapStyles.put(fmt.getFormatId(), cellStyle); + } else { + //hashMapStyles.put(fmt.getFormatId(), styleDefault); + hashMapStyles.put("default", styleDefault); + } + } + + } + }*/ + loadedStyles.putAll(hashMapStyles); + return loadedStyles; + } + + private void generate(XSSFWorkbook wb, SpreadsheetWriter sw, Map styles, ReportData rd, String sql_whole, ReportRuntime rr, HttpServletRequest request, XSSFSheet sheet) throws Exception { + HtmlStripper strip = new HtmlStripper(); + XSSFCellStyle styleCell = null; + XSSFCellStyle styleRowCell = null; + XSSFCellStyle styleDefaultCell = null; + + styleDefaultCell = (XSSFCellStyle) styles.get("default"); + + + // to check performance + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + + int rowNum = 0; + /*short s1 = 0, s2 = (short) (col-1); + rowNum += 1; + sw.insertRow(rowNum); + int styleIndex = styles.get("header").getIndex(); + sw.createCell(rowNum, reportTitle, styleIndex); + + //header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+reportTitle+"\n"+((Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0)?reportDescr:"")); + + // Report Description + if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { + sw.createCell(rowNum, reportDescr, styleIndex); + } + rowNum += 2; + sw.insertRow(rowNum);*/ + int cellNum = 0; + + + ColumnHeaderRow chr = null; + java.util.HashMap dataTypeMap = new java.util.HashMap(); + boolean firstPass = true; + int columnRows = rr.getVisibleColumnCount() ; + + HttpSession session = request.getSession(); + String drilldown_index = (String) session.getAttribute("drilldown_index"); + int index = 0; + try { + index = Integer.parseInt(drilldown_index); + } catch (NumberFormatException ex) { + index = 0; + } + String header = (String) session.getAttribute("TITLE_"+index); + String subtitle = (String) session.getAttribute("SUBTITLE_"+index); + if(nvl(header).length()>0) { + header = Utils.replaceInString(header, "
", " "); + header = Utils.replaceInString(header, "
", " "); + header = Utils.replaceInString(header, "
", " "); + header = strip.stripHtml(nvl(header).trim()); + subtitle = Utils.replaceInString(subtitle, "
", " "); + subtitle = Utils.replaceInString(subtitle, "
", " "); + subtitle = Utils.replaceInString(subtitle, "
", " "); + subtitle = strip.stripHtml(nvl(subtitle).trim()); + //XSSFRow row = sheet.createRow(rowNum); + sw.insertRow(rowNum); + cellNum = 0; + //XSSFCell cell = row.createCell(cellNum); + sw.createCell(cellNum, Utils.excelEncode(header)); + for (int i = 1; i <= columnRows; i++) { + sw.createCell(cellNum+i, ""); + } + sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); + sw.endRow(); +/* cell.setCellValue(Utils.excelEncode(header)); + cell.setCellStyle(styles.get("title")); +*/ //sw.createCell(cellNum,Utils.excelEncode(header), styles.get("title").getIndex()); +// sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); + rowNum += 1; +// row = sheet.createRow(rowNum); + sw.insertRow(rowNum); + cellNum = 0; +/* cell = row.createCell(cellNum); + cell.setCellValue(Utils.excelEncode(subtitle)); + cell.setCellStyle(styles.get("title")); +*/ //sw.createCell(cellNum,Utils.excelEncode(header), styles.get("title").getIndex()); + + sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); + sw.createCell(cellNum, Utils.excelEncode(subtitle)); + sw.endRow(); + //sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); +/* sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum,Utils.excelEncode(subtitle), styles.get("title").getIndex()); + sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); + +*/ rowNum += 1; + } + cellNum = 0; + String title = ""; + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + sw.insertRow(rowNum); + cellNum = -1; + /*if(rd.reportTotalRowHeaderCols!=null) { + cellNum +=1; + sw.createCell(cellNum, "No.", styles.get("header").getIndex()); + + //row.getCell((short) cellNum).setCellStyle(styleDataHeader); + }*/ + chr = rd.reportColumnHeaderRows.getNext(); + + if(nvl(sql_whole).length() <= 0 || (!rr.getReportType().equals(AppConstants.RT_LINEAR))) { + + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + title = rhc.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + + sw.createCell(cellNum,Utils.excelEncode(title), styles.get("header").getIndex()); + //sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum+columnRows, (short) (cellNum))); + //System.out.println(" **************** Row Header Title " + rhc.getColumnTitle() + " " + cellNum + " " ); + //System.out.println(cellNum + " " + cellWidth.size()); + } // for + + } + + firstPass = false; + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + cellNum += 1; + int colSpan = ch.getColSpan()-1; + title = ch.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + sw.createCell(cellNum, Utils.excelEncode(title), styles.get("header").getIndex()); + if(colSpan > 0) { + for ( int k = 1; k <= colSpan; k++ ) { + sw.createCell(cellNum+k, "", styles.get("header").getIndex()); + } + //sheet.addMergedRegion(new Region(rowNum, (short) cellNum, rowNum, (short) (cellNum+colSpan))); + } + if(colSpan > 0) + cellNum += colSpan; + } + } // for + rowNum += 1; + } // for + + sw.endRow(); + //All the possible combinations of date format + CreationHelper createHelper = wb.getCreationHelper(); + HashMap dateFormatMap = new HashMap(); + + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); + SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); + SimpleDateFormat YYYYMMDDDASHFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); + SimpleDateFormat DDMONYYHHMMFormat = new SimpleDateFormat("dd-MMM-yy HH:mm"); + SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); + SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); + SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat MMMMMDDYYYYHHMMSS = new SimpleDateFormat("MMMMM-dd-yyyy HH:mm:ss"); + + short dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yyyy"); + dateFormatMap.put("MMDDYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("yyyy/MM/dd"); + dateFormatMap.put("YYYYMMDD", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MMM yyyy"); + dateFormatMap.put("MONYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/yyyy"); + dateFormatMap.put("MMYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MMMMM dd, yyyy"); + dateFormatMap.put("MMMMMDDYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("yyyy-MM-dd"); + dateFormatMap.put("YYYYMMDDDASH", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"); + dateFormatMap.put("timestamp", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("dd-MMM-yyyy"); + dateFormatMap.put("MONTHYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MMMMM, yyyy"); + dateFormatMap.put("MMDDYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yyyy HH:mm:ss"); + dateFormatMap.put("MMDDYYYYHHMM", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yyyy HH:mm"); + dateFormatMap.put("MMDDYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("yyyy/MM/dd HH:mm:ss"); + dateFormatMap.put("YYYYMMDDHHMMSS", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("yyyy/MM/dd HH:mm"); + dateFormatMap.put("YYYYMMDDHHMM", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("dd-MMM-yyyy HH:mm:ss"); + dateFormatMap.put("DDMONYYYYHHMMSS", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("dd-MMM-yyyy HH:mm"); + dateFormatMap.put("DDMONYYYYHHMM", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("dd-MMM-yy HH:mm"); + dateFormatMap.put("DDMONYYHHMM", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("dd-MMM-yyyy"); + dateFormatMap.put("DDMONYYYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yy"); + dateFormatMap.put("MMDDYY", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yy HH:mm"); + dateFormatMap.put("MMDDYYHHMM", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yy HH:mm:ss"); + dateFormatMap.put("MMDDYYHHMMSS", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yyyy HH:mm z"); + dateFormatMap.put("MMDDYYYYHHMMZ", new Short(dateFormat)); + dateFormat = createHelper.createDataFormat().getFormat("MMMMM-dd-yyyy HH:mm:ss"); + dateFormatMap.put("MMMMMDDYYYYHHMMSS", new Short(dateFormat)); + + ResultSet rs = null; + Connection conn = null; + Statement st = null; + ResultSetMetaData rsmd = null; + + + if(nvl(sql_whole).length() >0 && (rr.getReportType().equals(AppConstants.RT_LINEAR) || rr.getReportType().equals(AppConstants.RT_HIVE) )) { + try { + conn = ConnectionUtils.getConnection(rr.getDbInfo()); + st = conn.createStatement(); + logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************")); + logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole)); + logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************")); + rs = st.executeQuery(sql_whole); + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + DataRow dr = null; + int j = 0; + int rowCount = 0; + while(rs.next()) { + + rowCount++; + + if(rowCount%10000 == 0) { + // to check performance + logger.debug(EELFLoggerDelegate.debugLogger, ("Performance check for "+rowCount+" starting**************")); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.totalMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + System.out.println(rowCount+"TH ROW****##### END #####"); + + // + } + sw.insertRow(rowNum); + cellNum = -1; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnLabel(i).toUpperCase(), strip.stripHtml(rs.getString(i))); + } + rd.reportDataRows.resetNext(); + dr = rd.reportDataRows.getNext(); + styleRowCell = null; + if (dr.isRowFormat() && styles != null) + styleRowCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); + j = 0; + //if(rowCount%1000 == 0) wb.write(sos); + + /*if(rd.reportTotalRowHeaderCols!=null) { + //cellNum = -1; + //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); + //if (firstPass) + // rhc.resetNext(); + //RowHeader rh = rhc.getRowHeader(rowCount-1); + sw.createCell(cellNum, rowCount, styleDefaultCell.getIndex()); + + //} // for + }*/ + firstPass = false; + //cellNum = -1; + for (dr.resetNext(); dr.hasNext();j++) { + styleCell = null; + //for (chr.resetNext(); chr.hasNext();) { + //ColumnHeader ch = chr.getNext(); + DataValue dv = dr.getNext(); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"","default")); + String value = nvl((String)colHash.get(dv.getColId().toUpperCase())); + + boolean bold = false; + + if(dv.isVisible()) { + cellNum += 1; + //System.out.println("Stripping HTML 1"); + //cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); + String dataType = (String) (dataTypeMap.get(dv.getColId())); + //System.out.println("Value " + value + " " + (( dataType !=null && dataType.equals("DATE")) || (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date"))) ); + if (dataType!=null && dataType.equals("NUMBER")){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(dv.getDisplayValue()); + //cellCurrencyNumber = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")){ + sw.createCell(cellNum,zInt,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + }else{ + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (dv.getDisplayValue().startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = dv.getDisplayValue().trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 1 is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value),styleRowCell.getIndex() ); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(value), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + + } + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (dv.getDisplayValue().startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT is "+tempInt); + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleRowCell!=null) + sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, tempInt, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempInt, styleCell.getIndex()); + else + sw.createCell(cellNum, tempInt, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleRowCell!=null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + } + } + } + } + + } else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || + (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { + XSSFCellStyle cellStyle = null; + if(styleRowCell!=null) { + cellStyle = styleRowCell; + } else if (styleCell!=null) { + cellStyle = styleCell; + } else { + cellStyle = styles.get(nvl(/*dv.getFormatId()*/"","date")); + } + + + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYY")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMMSS")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMM")); + flag = 1; + } + if(date==null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYY")); + flag = 1; + } + if(date==null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDD")); + flag = 1; + } + if(date==null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("timestamp")); + flag = 1; + } + if(date==null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MONYYYY")); + flag = 1; + } + if(date==null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMYYYY")); + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMMMMDDYYYY")); + flag = 1; + } + if(date==null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MONTHYYYY")); + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDHHMMSS")); + flag = 1; + } + if(date==null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDDASH")); + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDHHMM")); + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYYHHMMSS")); + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYYHHMM")); + flag = 1; + } + if(date==null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYHHMM")); + flag = 1; + } + if(date==null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYY")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYY")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMMZ")); + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMMMMDDYYYYHHMMSS")); + flag = 1; + } + + if(date!=null) { + //System.out.println("ExcelDate " + HSSFDateUtil.getExcelDate(date)); + Calendar cal=Calendar.getInstance(); + cal.setTime(date); + //sw.createCell(cellNum, cal,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + //if(styleRowCell!=null) + sw.createCell(cellNum, cal, cellStyle.getIndex()); + //else if (styleCell!=null) + //sw.createCell(cellNum, cal, cellStyle.getIndex()); + //else + //sw.createCell(cellNum, cal, cellStyle.getIndex()); + } else { + //cell.getCellStyle().setDataFormat((short)0); + //if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); + //else if (styleCell!=null) + //sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); + //else + //sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); + + } + //cellDate.setCellValue(date); + //cellDate.setCellValue(value); //cellDate.setCellValue(date); + //cellDate.setCellValue(dv.getDisplayValue()); + + } else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(dv.getDisplayValue()); + int zInt = 0; + if (value.equals("null")){ + if(styleRowCell!=null) + sw.createCell(cellNum, zInt, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, zInt, styleCell.getIndex()); + else + sw.createCell(cellNum, zInt, styleDefaultCell.getIndex()); + + } else { + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 2IF is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDoubleDollar,styleRowCell.getIndex() ); + else if (styleCell!=null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + + + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(","))!= -1){ + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + } + + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT 2 is "+tempInt); + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleRowCell!=null) + sw.createCell(cellNum, tempIntDollar,styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempIntDollar,styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempInt), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempInt),styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempInt), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleRowCell!=null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + + } + } + } else { + sw.createCell(cellNum, "", styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + } + } + } + + + } + else { + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); + if(styleRowCell!=null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleCell.getIndex()); + else { + if(nvl(value).startsWith(" ")) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styles.get(nvl(/*dv.getFormatId(),*/"","defaultLeft")).getIndex()); + else + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + + } + + } + + if (dv.isBold()) { + if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //cell.setCellStyle(styleCurrencyTotal); + } + else { + //cell.setCellStyle(styleTotal); + } + } else { + //cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); + continue; + } + //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"","default"))); + } //else if (bold == false) + //cell.setCellStyle(styleDefault); + } // dv.isVisible + + } + rowNum += 1; + sw.endRow(); + + } + if(rd.reportTotalRowHeaderCols!=null) { + rowCount++; + sw.insertRow(rowNum); + cellNum = -1; + rd.reportTotalRowHeaderCols.resetNext(); + cellNum += 1; + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + if (dr.isRowFormat() && styles != null) + styleRowCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); + + if(styleRowCell!=null) + sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleRowCell.getIndex()); + else + sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleDefaultCell.getIndex()); + rd.reportDataTotalRow.resetNext(); + //rd.reportDataTotalRow.getNext(); + DataRow drTotal = rd.reportDataTotalRow.getNext(); + if(drTotal!=null) { + drTotal.resetNext(); drTotal.getNext(); + for (; drTotal.hasNext();) { + DataValue dv = drTotal.getNext(); + if(dv.isVisible()) { + cellNum += 1; + styleCell = null; + String value = dv.getDisplayValue(); + sw.createCell(cellNum,value,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + } + } + rowNum += 1; + sw.endRow(); + } + + + + + +/* // To Display Total Values for Linear report + if(rd.reportDataTotalRow!=null) { + row = sheet.createRow(rowNum); + cellNum = -1; + rd.reportTotalRowHeaderCols.resetNext(); + //for (rd.reportTotalRowHeaderCols.resetNext(); rd.reportTotalRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); + //} + + DataRow drTotal = rd.reportDataTotalRow.getNext(); + //cellNum = -1; + for (drTotal.resetNext(); drTotal.hasNext();j++) { + cellNum += 1; + cell = row.createCell((short) cellNum); + DataValue dv = drTotal.getNext(); + String value = dv.getDisplayValue(); + cell.setCellValue(value); + boolean bold = false; + if (dv.isBold()) { + if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + cell.setCellStyle(styleCurrencyTotal); + } else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + } + }*/ + + } catch (SQLException ex) { + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + if(!(ex.getCause() instanceof java.net.SocketException) ) + throw new RaptorException (ex); + } finally { + try { + if(conn!=null) + conn.close(); + if(st!=null) + st.close(); + if(rs!=null) + rs.close(); + } catch (SQLException ex) { + throw new RaptorException(ex); + } + } + + String footer = (String) session.getAttribute("FOOTER_"+index); + if(nvl(footer).length()>0) { + footer = Utils.replaceInString(footer, "
", " "); + footer = Utils.replaceInString(footer, "
", " "); + footer = Utils.replaceInString(footer, "
", " "); + footer = strip.stripHtml(nvl(footer).trim()); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, footer.replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + } + + if(Globals.getShowDisclaimer()) { + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + + sw.createCell(cellNum, org.openecomp.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, org.openecomp.portalsdk.analytics.system.Globals.getFooterSecondLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + } + + } else { + //start data from rd + + int rowCount = 0; + DataRow dr = null; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + rowCount++; + + + dr = rd.reportDataRows.getNext(); + sw.insertRow(rowNum); + + cellNum = -1; + + if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) { + rd.reportRowHeaderCols.resetNext(0); + if(rd.reportTotalRowHeaderCols!=null) { + //cellNum = -1; + //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { + //a commented to suppress rownum + //a cellNum += 1; + //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); + //if (firstPass) + // rhc.resetNext(); + //RowHeader rh = rhc.getRowHeader(rowCount-1); + //a sw.createCell(cellNum, rowCount, styleDefaultCell.getIndex()); + //} // for + } + + } + firstPass = false; + //cellNum = -1; + int j = 0; + + for (dr.resetNext(); dr.hasNext();j++) { + DataValue dv = dr.getNext(); + styleCell = null; + boolean bold = false; + String value = nvl(dv.getDisplayValue()); + value = strip.stripHtml(value); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(/*dv.getFormatId(),*/"","default")); + + if(dv.isVisible()) { + cellNum += 1; + //cell = row.createCell((short) cellNum); + //System.out.println("Stripping HTML 1"); + //cell.setCellValue(strip.stripHtml(value)); + String dataType = (String) (dataTypeMap.get(dv.getColId())); + //System.out.println(" The Display Value is ********"+value + " " + dv.getDisplayTotal() + " " + dv.getColName()); + + if (dataType!=null && dataType.equals("NUMBER")){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(value); + //cellCurrencyNumber = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")){ + sw.createCell(cellNum,zInt,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + }else{ + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 1 is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value),styleRowCell.getIndex() ); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(value), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + + } + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT is "+tempInt); + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleRowCell!=null) + sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, tempInt, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempInt, styleCell.getIndex()); + else + sw.createCell(cellNum, tempInt, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleRowCell!=null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + + + } + //int temp = Integer.parseInt(value.trim()); + // cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + } + } + } + + }else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || + (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + if(date==null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if(date != null && flag == 0) { + flag = 1; + } + + + if(date!=null) { + Calendar cal=Calendar.getInstance(); + cal.setTime(date); + //sw.createCell(cellNum, cal,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); + if(styleRowCell!=null) + sw.createCell(cellNum, cal, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, cal, styleCell.getIndex()); + else + sw.createCell(cellNum, cal, styles.get(nvl(/*dv.getFormatId()*/"","date")).getIndex()); + + } else { + /*cell.getCellStyle().setDataFormat((short)0);*/ + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(value), styles.get(nvl(/*dv.getFormatId(),*/"","date")).getIndex()); + + } + //cellDate.setCellValue(date); + //cellDate.setCellValue(value); + + }else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + //cellNumber = row.createCell((short) cellNum); + //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); + //cellNumber.setCellValue(value); + int zInt = 0; + if (value.equals("null")){ + if(styleRowCell!=null) + sw.createCell(cellNum, zInt, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, zInt, styleCell.getIndex()); + else + sw.createCell(cellNum, zInt, styleDefaultCell.getIndex()); + } else { + + if ((value.indexOf("."))!= -1){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempDollar); + //System.out.println("Before copy Value |" + tempDollar); + //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); + //System.out.println("After copy Value |" + tempDollar); + if ((tempDollar.indexOf(","))!= -1){ + tempDollar = tempDollar.replaceAll(",", ""); + } + //System.out.println("The final string 2IF is "+tempDollar); + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDoubleDollar,styleRowCell.getIndex() ); + else if (styleCell!=null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + + + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(","))!= -1){ + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if(styleRowCell!=null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + } + + }else { + if (!(value.equals(""))){ + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //if (value.startsWith("$")){ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + //System.out.println("SUBSTRING |" + tempInt); + //System.out.println("Before copy Value |" + tempInt); + //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); + //System.out.println("After copy Value |" + tempInt); + if ((tempInt.indexOf(","))!= -1){ + tempInt = tempInt.replaceAll(",", ""); + } + //System.out.println("The final string INT 2 is "+tempInt); + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if(styleRowCell!=null) + sw.createCell(cellNum, tempIntDollar,styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, tempIntDollar,styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempInt), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempInt),styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempInt), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + }else{ + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(","))!= -1){ + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if(styleRowCell!=null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } catch (NumberFormatException ne) { + if(styleRowCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + } + //int temp = Integer.parseInt(value.trim()); + // cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + } else { + sw.createCell(cellNum, "", styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + } + } + + + } + else { + //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); + if(styleRowCell!=null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleRowCell.getIndex()); + else if (styleCell!=null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleCell.getIndex()); + else + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); + } + + //if (!(value.equals(""))){ + //int temp = Integer.parseInt(value.trim()); + //cell.setCellValue(temp); + //}else{ + // cell.setCellValue(strip.stripHtml(value)); + //} + //HSSFCellStyle styleFormat = null; + //HSSFCellStyle numberStyle = null; + //HSSFFont formatFont = null; + //short fgcolor = 0; + //short fillpattern = 0; + //System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + dv.getColName() ); + if (dv.isBold()) { + if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ + if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + //cell.setCellStyle(styleCurrencyTotal); + } + else { + //cell.setCellStyle(styleTotal); + } + } else { + //cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); + continue; + } + //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + // cell.setCellStyle((HSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"","default"))); + } //else if (bold == false) + //cell.setCellStyle(styleDefault); + } // if (dv.isVisible) + } // for + + /*for (int tmp=0; tmp0) { + footer = Utils.replaceInString(footer, "
", " "); + footer = Utils.replaceInString(footer, "
", " "); + footer = Utils.replaceInString(footer, "
", " "); + footer = strip.stripHtml(nvl(footer).trim()); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, footer.replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + } + + + if(Globals.getShowDisclaimer()) { + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + + sw.createCell(cellNum, org.openecomp.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, org.openecomp.portalsdk.analytics.system.Globals.getFooterSecondLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + } + + + } + // end data from rd + } + + // System.out.println(" Last Row " + wb.getSheetAt(0).getLastRowNum()); + } + + private void paintXSSFExcelParams(XSSFWorkbook wb,int rowNum,int col,ArrayList paramsList, String customizedParamInfo, XSSFSheet sheet, String reportTitle, String reportDescr) throws IOException { + //HSSFSheet sheet = wb.getSheet(getSheetName()); + int cellNum = 0; + XSSFRow row = null; + short s1 = 0, s2 = (short) 1; + HtmlStripper strip = new HtmlStripper(); + // Name Style + XSSFCellStyle styleName = wb.createCellStyle(); + //styleName.setFillBackgroundColor(HSSFColor.GREY_80_PERCENT.index); + styleName.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); + //styleName.setFillPattern(HSSFCellStyle.SPARSE_DOTS); + styleName.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleName.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleName.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleName.setBorderRight(HSSFCellStyle.BORDER_THIN); + styleName.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleName.setDataFormat((short)0); + XSSFFont font = wb.createFont(); + font.setFontHeight((short) (font_size / 0.05)); + font.setFontName("Tahoma"); + font.setColor(HSSFColor.BLACK.index); + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + styleName.setFont(font); + //Data Style + + // Create some fonts. + XSSFFont fontDefault = wb.createFont(); + // Initialize the styles & fonts. + // The default will be plain . + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (font_size / 0.05)); + fontDefault.setFontName("Tahoma"); + fontDefault.setItalic(true); + // Style default will be normal with no background + XSSFCellStyle styleValue = wb.createCellStyle(); + styleValue.setDataFormat((short)0); + styleValue.setAlignment(HSSFCellStyle.ALIGN_CENTER); + styleValue.setBorderBottom(HSSFCellStyle.BORDER_THIN); + styleValue.setBorderTop(HSSFCellStyle.BORDER_THIN); + styleValue.setBorderLeft(HSSFCellStyle.BORDER_THIN); + styleValue.setBorderRight(HSSFCellStyle.BORDER_THIN); + // styleValue.setFillForegroundColor(HSSFColor.YELLOW.index); + styleValue.setFillPattern(HSSFCellStyle.NO_FILL); + styleValue.setFont(fontDefault); + XSSFCell cell = null; + XSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HSSFCellStyle.ALIGN_CENTER); +// styleDescription.setBorderBottom(HSSFCellStyle.BORDER_THIN); +// styleDescription.setBorderTop(HSSFCellStyle.BORDER_THIN); +// styleDescription.setBorderRight(HSSFCellStyle.BORDER_THIN); +// styleDescription.setBorderLeft(HSSFCellStyle.BORDER_THIN); + XSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) (font_header_descr_size / 0.05)); + fontDescr.setFontName("Tahoma"); + fontDescr.setColor(HSSFColor.BLACK.index); + fontDescr.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + styleDescription.setFont(font); + XSSFCell cellDescr = null; + int paramSeq = 0; + Header header = sheet.getHeader(); + StringBuffer strBuf = new StringBuffer(); + if(!Globals.customizeFormFieldInfo() || customizedParamInfo.length()<=0) { + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + //System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); + if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if(paramSeq <= 1) { + row = sheet.createRow(++rowNum); + cell = row.createCell((short) 0); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); + cellDescr = row.createCell((short) 0); + cellDescr.setCellValue("Run-time Parameters"); + cellDescr.setCellStyle(styleDescription); + + + strBuf.append(reportTitle+"\n"); + //strBuf.append("Run-time Parameters\n"); + } + row = sheet.createRow(++rowNum); + cellNum = 0; + //System.out.println("RowNum " + rowNum + " " + value.getId() + " " +value.getName()); + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getId()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getName().replaceAll("~",",")); + cell.setCellStyle(styleValue); + + //strBuf.append(value.getId()+": "+ value.getName()+"\n"); + } + } //for + } else { + strBuf.append(reportTitle+"\n"); + Document document = new Document(); + document.open(); + HTMLWorker worker = new HTMLWorker(document); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("body", "leading", "16,0"); + ArrayList p = HTMLWorker.parseToList(new StringReader(customizedParamInfo), style); + String name = ""; + String token = ""; + String value = ""; + String s = ""; + PdfPTable pdfTable = null; + for (int k = 0; k < p.size(); ++k){ + if(p.get(k) instanceof Paragraph) + s = ((Paragraph)p.get(k)).toString(); + else { /*if ((p.get(k) instanceof PdfPTable))*/ + pdfTable = ((PdfPTable)p.get(k)); + } + //todo: Logic for parsing pdfTable should be added after upgrading to iText 5.0.0 + //s = Utils.replaceInString(s, ",", "|"); + s = s.replaceAll(",", "|"); + s = s.replaceAll("~", ","); + if(s.indexOf(":")!= -1) { + //System.out.println("|"+s+"|"); + row = sheet.createRow(++rowNum); + cell = row.createCell((short) 0); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); + cellDescr = row.createCell((short) 0); + cellDescr.setCellValue("Run-time Parameters"); + cellDescr.setCellStyle(styleDescription); + + //strBuf.append("Run-time Parameters\n"); + StringTokenizer st = new StringTokenizer(s.trim(), "|"); + while(st.hasMoreTokens()) { + token = st.nextToken(); + token = token.trim(); + if (!(token.trim().equals("|") || token.trim().equals("]]") || token.trim().equals("]") || token.trim().equals("[") )) { + if(token.endsWith(":")) { + name = token; + name = name.substring(0, name.length()-1); + if(name.startsWith("[")) + name = name.substring(1); + value = st.nextToken(); + if(nvl(value).endsWith("]"))value = nvl(value).substring(0, nvl(value).length()-1); + } /*else if(name != null && name.length() > 0) { + value = st.nextToken(); + if(value.endsWith("]]"))value = value.substring(0, value.length()-1); + }*/ + if(name!=null && name.trim().length()>0) { + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(name.trim()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.trim()); + cell.setCellStyle(styleValue); + //strBuf.append(name.trim()+": "+ value.trim()+"\n"); + } +/* if(token.endsWith(":") && (value!=null && value.trim().length()<=0) && (name!=null && name.trim().length()>0 && name.endsWith(":"))) { + name = name.substring(0, name.indexOf(":")+1); + //value = token.substring(token.indexOf(":")+1); + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(name.trim()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.trim()); + cell.setCellStyle(styleValue); + + //strBuf.append(name.trim()+": "+ value.trim()+"\n"); + value = ""; + name = ""; + } +*/ } + int cw = 0; + cw = name.trim().length() + 12; + // if(i!=cellWidth.size()-1) + if(sheet.getColumnWidth((short)0)< (short) name.trim().length()) + sheet.setColumnWidth((short)0, (short) name.trim().length()); + if(sheet.getColumnWidth((short)1)< (short) value.trim().length()) + sheet.setColumnWidth((short)1, (short) value.trim().length()); + name = ""; + value = ""; + + } + + try { + SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); + Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); + SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); + + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue("Report Date/Time"); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + + cell.setCellValue(dtimestamp.format(sysdate)+" "+Globals.getTimeZone()); + cell.setCellStyle(styleValue); + + } catch(Exception ex) { + //ex.printStackTrace(); + } + + + } + } + + +/* Iterator iter1 = paramsList.iterator(); + s1 = 0; s2 = (short)10; + if(iter1.hasNext()) { + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + sheet.addMergedRegion(new Region(rowNum, s1, rowNum, s2)); + cell.setCellValue(strip.stripHtml(customizedParamInfo)); + } +*/ +/* rowNum += 2; + row = sheet.createRow(rowNum);*/ + } // if + Iterator iterCheck = paramsList.iterator(); + if(iterCheck.hasNext()) { + rowNum += 2; + row = sheet.createRow(rowNum); + } + header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) font_header_title_size)+strBuf.toString()); + } + + // Trying different --> + public void createHTMLFileContent(Writer out, ReportData rd, + ReportRuntime rr, String sql_whole, HttpServletRequest request, HttpServletResponse response) + throws RaptorException, IOException { + //response.setContentType("application/vnd.ms-excel"); + //response.setHeader("Content-disposition", + // "attachment; filename=" + + // "Example.xls" ); + PrintWriter csvOut = response.getWriter(); + HtmlStripper strip = new HtmlStripper(); + ResultSet rs = null; + Connection conn = null; + Statement st = null; + ResultSetMetaData rsmd = null; + ColumnHeaderRow chr = null; + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + csvOut.println("\n" + + "" + rr.getReportName() + "\n" + + "\n" ); + System.out.println("HTML-Excel Generation Triggered: " + new java.util.Date()); + csvOut.print(""); + if (Globals.getPrintParamsInCSVDownload()) { + ArrayList paramsList = rr.getParamNameValuePairsforPDFExcel(request, 1); + int paramSeq = 0; + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + //System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); + if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if(paramSeq <= 1) { + csvOut.println(""); + //strBuf.append("Run-time Parameters\n"); + } + csvOut.println(""); + csvOut.println(""); + csvOut.println(""); + + //strBuf.append(value.getId()+": "+ value.getName()+"\n"); + } + } //for + csvOut.println(""); + csvOut.println(""); + System.out.println("HTML-Excel: Header Rendering complete " + new java.util.Date()); + } + int rowCount = 0; + if(nvl(sql_whole).length()>0) { + try { + conn = ConnectionUtils.getConnection(rr.getDbInfo()); + st = conn.createStatement(); + Log.write("[SQL] " + sql_whole, 4); + int downloadLimit = Globals.getDownloadLimit(); + Callable callable = new ExecuteQuery(st, sql_whole, downloadLimit); + ExecutorService executor = new ScheduledThreadPoolExecutor(5); + System.out.println("Time Started" + new java.util.Date()); + Future future = executor.submit(callable); + try { + rs = future.get(900, TimeUnit.SECONDS); + } catch (TimeoutException ex) { + System.out.println("Cancelling Query"); + st.cancel(); + System.out.println("Query Cancelled"); + throw new Exception("user requested"); + } + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + + if(rd!=null) { + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + chr = rd.reportColumnHeaderRows.getNext(); + csvOut.println(""); + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + csvOut.print(""); + //for (int i = 1; i < ch.getColSpan(); i++) + // csvOut.print(","); + + } + } // for + csvOut.println(""); + } // for + + + while(rs.next()) { + csvOut.println(""); +/* if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { + csvOut.print(Globals.getUserDefinedMessageForMemoryLimitReached() + " " + rowCount +"records out of " + rr.getReportDataSize() + " were downloaded to CSV."); + break; + } +*/ rowCount++; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnName(i), rs.getString(i)); + } + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + csvOut.println(""); + } + + } + csvOut.println(""); + } + System.out.println("Downloaded Rows in HTML-Excel " + rowCount + " : "+ new java.util.Date()); + if(rowCount == 0) { + csvOut.print(""); + } else { + } + } else { + csvOut.println(""); + } + csvOut.println("
" + "Run-time Parameters" + "
" + value.getId() +"" + value.getName().replaceAll("~",",")+ "
 
 
" + ch.getColumnTitle() + "
" + strip.stripCSVHtml(nvl((String)colHash.get(ch.getLinkColId().toUpperCase()))) + "
No Data Found
No Data Found
\n"); + + } catch (SQLException ex) { + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + throw new RaptorException (ex); + } finally { + try { + if(conn!=null) + conn.close(); + if(st!=null) + st.close(); + if(rs!=null) + rs.close(); + } catch (SQLException ex) { + throw new RaptorException(ex); + } + } + //csvOut.flush(); + } else { + boolean firstPass = true; + int numberOfColumns = 0; + if(rd!=null) { + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + chr = rd.reportColumnHeaderRows.getNext(); + csvOut.println(""); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + + if (firstPass) { + numberOfColumns++; + csvOut.print("" + rhc.getColumnTitle() + ""); + } + //csvOut.print(","); + } // for + + + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if(ch.isVisible()) { + if(firstPass) numberOfColumns++; + csvOut.print("" + ch.getColumnTitle() + ""); + //for (int i = 1; i < ch.getColSpan(); i++) + //csvOut.print(","); + } + } // for + firstPass = false; + csvOut.println(""); + } // for + + firstPass = true; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + DataRow dr = rd.reportDataRows.getNext(); + csvOut.println(""); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + + csvOut.print("" + strip.stripCSVHtml(rh.getRowTitle()) + ""); + } // for + firstPass = false; + + for (dr.resetNext(); dr.hasNext();) { + DataValue dv = dr.getNext(); + if(dv.isVisible()) + csvOut.print("" + strip.stripCSVHtml(dv.getDisplayValue()) + ""); + } // for + + csvOut.println(""); + + } // for + //csvOut.flush(); + } else { + csvOut.println("No Data Found"); + } + } + csvOut.println("\n"); + System.out.println("HTML-Excel Generation: Data Rendering complete " + new java.util.Date()); + System.out.println("##### Heap utilization statistics [MB] #####"); + System.out.println("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb); + System.out.println("Free Memory:" + + runtime.freeMemory() / mb); + System.out.println("Total Memory:" + runtime.totalMemory() / mb); + System.out.println("Max Memory:" + runtime.maxMemory() / mb); + + } // createCSVFileContent + + /** + * Checking if every row and cell in merging region exists, and create those which are not + * @param sheet in which check is performed + * @param region to check + * @param cellStyle cell style to apply for whole region + */ + private void cleanBeforeMergeOnValidCells(XSSFSheet sheet,CellRangeAddress region, XSSFCellStyle cellStyle ) + { + for(int rowNum =region.getFirstRow();rowNum<=region.getLastRow();rowNum++){ + XSSFRow row= sheet.getRow(rowNum); + if(row==null){ + sheet.createRow(rowNum); + } + for(int colNum=region.getFirstColumn();colNum<=region.getLastColumn();colNum++){ + XSSFCell currentCell = row.getCell(colNum); + if(currentCell==null){ + currentCell = row.createCell(colNum); + } + + currentCell.setCellStyle(cellStyle); + + } + } + + + } +} // ReportHandler + + +/** + * Adapter for a Writer to behave like an OutputStream. + * + * Bytes are converted to chars using the platform default encoding. + * If this encoding is not a single-byte encoding, some data may be lost. + */ + class WriterOutputStream extends OutputStream { + + private final Writer writer; + + public WriterOutputStream(Writer writer) { + this.writer = writer; + } + + public void write(int b) throws IOException { + // It's tempting to use writer.write((char) b), but that may get the encoding wrong + // This is inefficient, but it works + write(new byte[] {(byte) b}, 0, 1); + } + + public void write(byte b[], int off, int len) throws IOException { + writer.write(new String(b, off, len)); + } + + public void flush() throws IOException { + writer.flush(); + } + + public void close() throws IOException { + writer.close(); + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportLoader.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportLoader.java new file mode 100644 index 00000000..ddbf442c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/ReportLoader.java @@ -0,0 +1,1079 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * ReportLoader.java - This class is used to call database interaction related to reports. + * ------------------------------------------------------------------------------------------- + * + * + * + * Changes + * ------- + * 28-Aug-2009 : Version 8.5.1 (Sundar);
  • isDashboardType is made to return false, as any report can be added to Dashboard.
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 27-Jul-2009 : Version 8.4 (Sundar);
  • Admin User is given the same privilege as Super User when the property + * "admin_role_equiv_to_super_role" in raptor.properties is Y. A check is made in corresponding to that.
+ * + */ +package org.openecomp.portalsdk.analytics.model; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Vector; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.ReportSQLException; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.model.base.ReportWrapper; +import org.openecomp.portalsdk.analytics.model.definition.ReportLogEntry; +import org.openecomp.portalsdk.analytics.model.search.ReportSearchResult; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.DbUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.system.fusion.domain.QuickLink; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class ReportLoader extends org.openecomp.portalsdk.analytics.RaptorObject { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportLoader.class); + + + //private static Properties sqlProperty; + + public static String loadCustomReportXML(String reportID) throws RaptorException { + Connection connection = DbUtils.getConnection(); + try { + return loadCustomReportXML(connection, reportID); + } finally { + DbUtils.clearConnection(connection); + } + } // loadCustomReportXML + + public static String loadCustomReportXML(Connection connection, String reportID) + throws RaptorException { + + StringBuffer sb = new StringBuffer(); + + PreparedStatement stmt = null; + + ResultSet rs = null; + + try { + + String sql = Globals.getLoadCustomReportXml(); + stmt = connection.prepareStatement(sql); + stmt.setInt(1,Integer.parseInt(reportID)); + rs = stmt.executeQuery(); + if(Globals.isWeblogicServer()) { + java.sql.Clob clob= null; + Object obj = null; + if (rs.next()) { + clob = rs.getClob(1); + } + else + throw new RaptorException("Report " + reportID + " not found in the database"); + + int len = 0; + char[] buffer = new char[512]; + Reader in = null; + in = new InputStreamReader(clob.getAsciiStream()); + // if(obj instanceof oracle.sql.CLOB) { + // in = ((oracle.sql.CLOB) obj).getCharacterStream(); + // } else if (obj instanceof weblogic.jdbc.wrapper.Clob) { + // in = ((weblogic.jdbc.base.BaseClob) obj).getCharacterStream(); + // } + while ((len = in.read(buffer)) != -1) + sb.append(buffer, 0, len); + in.close(); + } else if (Globals.isPostgreSQL() || Globals.isMySQL()) { + String clob= null; + Object obj = null; + if (rs.next()) { + sb.append(rs.getString(1)); + } + else + throw new RaptorException("Report " + reportID + " not found in the database"); + } else { + /*oracle.sql.CLOB clob = null; + if (rs.next()) + clob = (oracle.sql.CLOB) rs.getObject(1); + else + throw new RaptorException("Report " + reportID + " not found in the database"); + int len = 0; + char[] buffer = new char[512]; + Reader in = clob.getCharacterStream(); + while ((len = in.read(buffer)) != -1) + sb.append(buffer, 0, len); + in.close();*/ + throw new RaptorException("only maria db support for this "); + } + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } catch (IOException ex) { + throw new RaptorException (ex.getMessage(), ex.getCause()); + } finally { + try { + if(rs!=null) + rs.close(); + if(stmt!=null) + stmt.close(); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + return sb.toString(); + } // loadCustomReportXML + + private static void dbUpdateReportXML(Connection connection, String reportID, + String reportXML) throws RaptorException { + PreparedStatement stmt = null; + ResultSet rs = null; + + try { + String sql = ""; + if(!Globals.isMySQL()) + sql = Globals.getDBUpdateReportXml(); + else + sql = Globals.getDBUpdateReportXmlMySqlSelect(); + stmt = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE, + ResultSet.CONCUR_UPDATABLE); + stmt.setInt(1,Integer.parseInt(reportID)); + rs = stmt.executeQuery(); + Writer out = null; + /*if(Globals.isWeblogicServer()) { + java.sql.Clob clob = null; + if (rs.next()) + clob = rs.getClob(1); + else + throw new RaptorException("Report " + reportID + " not found in the database"); + + if (clob.length() > reportXML.length()) + clob.truncate(0); + //clob.trim(reportXML.length()); + out = ((weblogic.jdbc.vendor.oracle.OracleThinClob)clob).getCharacterOutputStream(); + } else*/ + if (Globals.isPostgreSQL()) { + if (rs.next()) { + rs.updateString("report_xml",reportXML); + rs.updateRow(); + connection.commit(); + //sb.append(rs.getString(1)); + } + else + throw new RaptorException("Report " + reportID + " not found in the database"); + } else if (Globals.isMySQL()) { + if(rs.next()) { + final InputStream stream = rs.getBinaryStream( "report_xml" ); + InputStream streamNew = new ByteArrayInputStream(reportXML.getBytes(StandardCharsets.UTF_8)); + final PreparedStatement update = connection.prepareStatement( Globals.getDBUpdateReportXmlMySql() ); + update.setBinaryStream( 1,streamNew ); + update.setInt( 2,Integer.parseInt(reportID) ); + update.execute(); + } else + throw new RaptorException("Report " + reportID + " not found in the database"); + + } else { + /*oracle.sql.CLOB clob = null; + if (rs.next()) + clob = (oracle.sql.CLOB) rs.getObject(2); + else + throw new RaptorException("Report " + reportID + " not found in the database"); + + if (clob.length() > reportXML.length()) + clob.trim(reportXML.length()); + out = clob.getCharacterOutputStream();*/ + throw new RaptorException("only maria db support for this "); + } + if(!(Globals.isPostgreSQL() || Globals.isMySQL())) { + out.write(reportXML); + out.flush(); + out.close(); + } + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } catch (IOException ex) { + throw new RaptorException (ex.getMessage(), ex.getCause()); + } finally { + try { + if(rs!=null) + rs.close(); + if(stmt!=null) + stmt.close(); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + } // dbUpdateReportXML + + public static void updateCustomReportRec(Connection connection, ReportWrapper rw, + String reportXML) throws RaptorException { + /* DbUtils.executeUpdate(connection,"UPDATE cr_report SET title='" + + Utils.oracleSafe(rw.getReportName()) + "', descr='" + + Utils.oracleSafe(rw.getReportDescr()) + "', public_yn='" + + (rw.isPublic() ? "Y" : "N") + "', menu_id='" + rw.getMenuID() + + "', menu_approved_yn='" + (rw.isMenuApproved() ? "Y" : "N") + "', owner_id=" + + rw.getOwnerID() + ", maint_id=" + rw.getUpdateID() + + ", maint_date=TO_DATE('" + rw.getUpdateDate() + "', '" + + Globals.getOracleTimeFormat() + "'), dashboard_type_yn='"+ (rw.isDashboardType()?"Y":"N")+"', dashboard_yn= '" + + (rw.getReportType().equals(AppConstants.RT_DASHBOARD)?"Y":"N") + "' WHERE rep_id = " + rw.getReportID());*/ + + String sql = Globals.getUpdateCustomReportRec(); + + sql = sql.replace("[Utils.oracleSafe(rw.getReportName())]", Utils.oracleSafe(rw.getReportName())); + sql = sql.replace("[Utils.oracleSafe(rw.getReportDescr())]", Utils.oracleSafe(rw.getReportDescr())); + sql = sql.replace("[(rw.isPublic()]",(rw.isPublic() ? "Y" : "N")); + sql = sql.replace("[rw.getMenuID()]", rw.getMenuID()); + sql = sql.replace("[(rw.isMenuApproved()]", (rw.isMenuApproved() ? "Y" : "N")); + sql = sql.replace("[rw.getOwnerID()]",rw.getOwnerID()); + sql = sql.replace("[rw.getUpdateID()]",rw.getUpdateID()); + sql = sql.replace("[rw.getUpdateDate()]",rw.getUpdateDate()); + sql = sql.replace("[Globals.getTimeFormat()]", Globals.getTimeFormat()); + sql = sql.replace("[(rw.isDashboardType()]", (rw.isDashboardType()?"Y":"N")); + sql = sql.replace("[(rw.getReportType().equals(AppConstants.RT_DASHBOARD)]", (rw.getReportType().equals(AppConstants.RT_DASHBOARD)?"Y":"N")); + sql = sql.replace("[rw.getReportID()]", rw.getReportID()); + + DbUtils.executeUpdate(connection, sql); + + dbUpdateReportXML(connection, rw.getReportID(), reportXML); + } // updateCustomReportRec + + public static boolean isDashboardType ( String reportID ) throws RaptorException { + return false; +/* String sql = "select dashboard_type_yn from cr_report where rep_id = ?"; + Connection connection = DbUtils.getConnection(); + PreparedStatement stmt = null; + ResultSet rs = null; + boolean dashboardType= false; + try { + stmt = connection.prepareStatement(sql); + stmt.setString(1, reportID); + rs = stmt.executeQuery(); + if(rs.next()) { + dashboardType = nvls(rs.getString(1),"N").trim().toUpperCase().startsWith("Y"); + } + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } finally { + try { + rs.close(); + stmt.close(); + DbUtils.clearConnection(connection); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + return dashboardType;*/ + } + + public static boolean isReportsAlreadyScheduled ( String reportID ) throws RaptorException { + //String sql = "select rep_id from cr_report_schedule where rep_id = ?"; + String sql = Globals.getIsReportAlreadyScheduled(); + + Connection connection = DbUtils.getConnection(); + PreparedStatement stmt = null; + ResultSet rs = null; + boolean isScheduled= false; + try { + stmt = connection.prepareStatement(sql); + stmt.setInt(1, Integer.parseInt(reportID)); + rs = stmt.executeQuery(); + if(rs.next()) { + isScheduled = true; + } + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } finally { + try { + if(rs!=null) + rs.close(); + if(stmt!=null) + stmt.close(); + DbUtils.clearConnection(connection); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + return isScheduled; +} + + public static void createCustomReportRec(Connection connection, ReportWrapper rw, + String reportXML) throws RaptorException { + + /*DbUtils + .executeUpdate( + connection, + "INSERT INTO cr_report(rep_id, title, descr, public_yn, menu_id, menu_approved_yn, report_xml, owner_id, create_id, create_date, maint_id, maint_date, dashboard_type_yn, dashboard_yn, folder_id) VALUES(" + + rw.getReportID() + + ", '" + + Utils.oracleSafe(rw.getReportName()) + + "', '" + + Utils.oracleSafe(rw.getReportDescr()) + + "', '" + + (rw.isPublic() ? "Y" : "N") + + "', '" + + rw.getMenuID() + + "', '" + + (rw.isMenuApproved() ? "Y" : "N") + + "', '', " + + rw.getOwnerID() + + ", " + + rw.getCreateID() + + ", TO_DATE('" + + rw.getCreateDate() + + "', '" + + Globals.getOracleTimeFormat() + + "'), " + + rw.getUpdateID() + + ", TO_DATE('" + + rw.getUpdateDate() + + "', '" + + Globals.getOracleTimeFormat() + + "'), '" + + (rw.isDashboardType()?"Y":"N") + + "', '" + + (rw.getReportType().equals(AppConstants.RT_DASHBOARD)?"Y":"N") + + "', " + + rw.getFolderId() + + ")");*/ + String sql = Globals.getCreateCustomReportRec(); + + sql = sql.replace("[rw.getReportID()]", rw.getReportID()); + sql = sql.replace("[Utils.oracleSafe(rw.getReportName())]", Utils.oracleSafe(rw.getReportName())); + sql = sql.replace("[Utils.oracleSafe(rw.getReportDescr())]", Utils.oracleSafe(rw.getReportDescr())); + sql = sql.replace("[rw.isPublic()]", (rw.isPublic() ? "Y" : "N")); + sql = sql.replace("[rw.getMenuID()]", rw.getMenuID()); + sql = sql.replace("[rw.isMenuApproved()]", (rw.isMenuApproved() ? "Y" : "N")); + sql = sql.replace("[rw.getOwnerID()]", rw.getOwnerID()); + sql = sql.replace("[rw.getCreateID()]", rw.getCreateID()); + sql = sql.replace("[rw.getCreateDate()]", rw.getCreateDate()); + sql = sql.replace("[Globals.getTimeFormat()]", Globals.getTimeFormat()); + sql = sql.replace("[rw.getUpdateID()]", rw.getUpdateID()); + sql = sql.replace("[rw.getUpdateDate()]", rw.getUpdateDate()); + sql = sql.replace("[rw.isDashboardType()]", (rw.isDashboardType()?"Y":"N")); + sql = sql.replace("[rw.getReportType().equals(AppConstants.RT_DASHBOARD)]", (rw.getReportType().equals(AppConstants.RT_DASHBOARD)?"Y":"N")); + sql = sql.replace("[rw.getFolderId()]", rw.getFolderId()); + + + DbUtils.executeUpdate(connection,sql); + + dbUpdateReportXML(connection, rw.getReportID(), reportXML); + } // createCustomReportRec + + public static Vector getUserReportNames(HttpServletRequest request) { + return getUserReportNames(AppUtils.getUserID(request)); + } // getUserReportNames + + public static Vector getUserReportNames(String userID) { + Vector reportIdNames = new Vector(); + + try { + + String sql = Globals.getTheUserReportNames(); + sql = sql.replace("[userID]", userID); + DataSet ds = DbUtils.executeQuery(sql); + + //DataSet ds = DbUtils + // .executeQuery("SELECT cr.rep_id, cr.title FROM cr_report cr WHERE nvl(cr.owner_id, cr.create_id) = " + // + userID); + + for (int i = 0; i < ds.getRowCount(); i++) + reportIdNames.add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1))); + } catch (Exception e) { + } + + return reportIdNames; + } // getUserReportNames + + public static String getReportOwnerID(String reportID) throws RaptorException { + + // String sql = "SELECT nvl(cr.owner_id, cr.create_id) owner FROM cr_report cr WHERE rep_id = ?"; + + String sql = Globals.getTheReportOwnerId(); + + Connection connection = DbUtils.getConnection(); + PreparedStatement stmt = null; + ResultSet rs = null; + String reportOwnerID = null; + try { + stmt = connection.prepareStatement(sql); + stmt.setInt(1, Integer.parseInt(reportID)); + rs = stmt.executeQuery(); + if(rs.next()) { + reportOwnerID = rs.getString(1); + } + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } finally { + try { + if(rs!=null) + rs.close(); + if(stmt!=null) + stmt.close(); + DbUtils.clearConnection(connection); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + + return reportOwnerID; + } // getReportOwnerID + + public static void deleteReportRecord(String reportID) throws RaptorException { + Connection con = DbUtils.startTransaction(); + + /*try { + DbUtils.executeUpdate(con, "DELETE cr_report_log WHERE rep_id = " + reportID); + DbUtils.executeUpdate(con, "DELETE cr_report_schedule_users WHERE rep_id = " + + reportID); + DbUtils.executeUpdate(con, "DELETE cr_report_schedule WHERE rep_id = " + reportID); + DbUtils.executeUpdate(con, "DELETE cr_report_access WHERE rep_id = " + reportID); + DbUtils.executeUpdate(con, "DELETE cr_report_email_sent_log WHERE rep_id = " + reportID); + DbUtils.executeUpdate(con, "DELETE cr_favorite_reports WHERE rep_id = " + reportID); + DbUtils.executeUpdate(con, "DELETE cr_report WHERE rep_id = " + reportID); + DbUtils.commitTransaction(con); + } */ + + try{ + String sql1= Globals.getDeleteReportRecordLog(); + sql1 = sql1.replace("[reportID]", reportID); + String sql2= Globals.getDeleteReportRecordUsers(); + sql2 = sql2.replace("[reportID]", reportID); + String sql3= Globals.getDeleteReportRecordSchedule(); + sql3 = sql3.replace("[reportID]", reportID); + String sql4= Globals.getDeleteReportRecordAccess(); + sql4 = sql4.replace("[reportID]", reportID); + String sql5= Globals.getDeleteReportRecordEmail(); + sql5 = sql5.replace("[reportID]", reportID); + String sql6= Globals.getDeleteReportRecordFavorite(); + sql6 = sql6.replace("[reportID]", reportID); + String sql7= Globals.getDeleteReportRecordReport(); + sql7 = sql7.replace("[reportID]", reportID); + + DbUtils.executeUpdate(con, sql1); + DbUtils.executeUpdate(con, sql2); + DbUtils.executeUpdate(con, sql3); + DbUtils.executeUpdate(con, sql4); + DbUtils.executeUpdate(con, sql5); + DbUtils.executeUpdate(con, sql6); + DbUtils.executeUpdate(con, sql7); + DbUtils.commitTransaction(con); + + } + + + catch (Exception e) { + DbUtils.rollbackTransaction(con); + } finally { + DbUtils.clearConnection(con); + } + } // deleteReportRecord + + public static ArrayList loadQuickLinks(HttpServletRequest request, String menuId, boolean b) throws RaptorException { + String userID = AppUtils.getUserID(request); + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + + // DataSet ds = DbUtils.executeQuery("SELECT cr.rep_id, cr.title FROM + // cr_report cr WHERE cr.public_yn = 'Y' AND cr.menu_id = + // '"+nvls(menuId)+"' AND cr.menu_approved_yn = 'Y' ORDER BY cr.title"); + // Copied from SearchHandler and simplified + /*String query = "SELECT cr.rep_id, " + + "cr.title, " + + "cr.descr " + + "FROM cr_report cr, " + + "(SELECT rep_id, " + + "MIN(read_only_yn) read_only_yn " + + "FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = " + + userID + + ") " + + "UNION ALL " + + "(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN (" + + roleList.toString() + "))" + ") report_access " + + "GROUP BY rep_id) ra " + "WHERE INSTR('|'||cr.menu_id||'|', '|'||'" + + nvls(menuId) + "'||'|') > 0 AND " + "cr.menu_approved_yn = 'Y' AND " + + "cr.rep_id = ra.rep_id (+) AND " + + "(nvl(cr.owner_id, cr.create_id) = " + userID + + " OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) " + + "ORDER BY cr.title";*/ + + String query = Globals.getLoadQuickLinks(); + query = query.replace("[userID]", userID); + query = query.replace("[roleList.toString()]", roleList.toString()); + query = query.replace("[nvls(menuId)]", nvls(menuId)); + + DataSet ds = DbUtils + .executeQuery(query); + + ArrayList quickLinks = new ArrayList(ds.getRowCount()); + StringBuffer link = new StringBuffer(""); + for (int i = 0; i < ds.getRowCount(); i++) { + link = new StringBuffer(""); + link.append("" +ds.getString(i, 1) + "" + (Globals.getShowDescrAtRuntime() ? " - " + ds.getString(i, 2) : "") ); + quickLinks.add(link.toString()); + } + + return quickLinks; + } // loadQuickLinks + + public static ArrayList getQuickLinksJSON(HttpServletRequest request, String menuId, boolean b) throws RaptorException { + String userID = AppUtils.getUserID(request); + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + + String query = Globals.getLoadQuickLinks(); + query = query.replace("[userID]", userID); + query = query.replace("[roleList.toString()]", roleList.toString()); + query = query.replace("[nvls(menuId)]", nvls(menuId)); + + DataSet ds = DbUtils + .executeQuery(query); + + ArrayList quickLinksArray = new ArrayList(ds.getRowCount()); + for (int i = 0; i < ds.getRowCount(); i++) { + QuickLink quickLink = new QuickLink(); + StringBuffer link = new StringBuffer(""); + link.append(AppUtils.getReportExecuteActionURLNG() +"c_master="+ ds.getString(i, 0)); + if(b) link.append("&PAGE_ID="+menuId+"&refresh=Y"); + quickLink.setReportURL(link.toString()); + quickLink.setReportName(ds.getString(i, 1)); + quickLink.setShowDescr(Globals.getShowDescrAtRuntime()); + quickLink.setReportDescr(ds.getString(i, 2)); + quickLinksArray.add(quickLink); + } + + return quickLinksArray; + } // loadQuickLinks + + //this will retrieve all the reports within the specified folder. + public static ReportSearchResult loadFolderReports(HttpServletRequest request, String menuId, boolean b, String folderId, boolean isUserReport, boolean isPublicReport) throws RaptorException { + String HTML_FORM = "forma"; + String userID = AppUtils.getUserID(request); + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + String rep_title_sql = "''"; + String PRIVATE_ICON = "Private "; + + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + + /*String sql= "SELECT cr.rep_id, " + + "cr.rep_id report_id, " + + rep_title_sql+ + "||DECODE(cr.public_yn, 'Y', '', '" + + PRIVATE_ICON + + "')||cr.title||'' title, " + + "cr.descr, " + + "au.first_name||' '||au.last_name owner_name, " + + "TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + + userID + + ", 'N', NVL(ra.read_only_yn, 'Y')) read_only_yn, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + + userID + + ", 'Y', 'N') user_is_owner_yn " + + " FROM cr_report cr, " + + "app_user au, " + + "(SELECT rep_id, MIN(read_only_yn) read_only_yn " + + "FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = " + + userID + + ") " + + "UNION ALL " + + "(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN " + + "(-1,1000,1))" + ") report_access GROUP BY rep_id) ra " + + "WHERE TO_CHAR(cr.rep_id) = nvl('', TO_CHAR(cr.rep_id)) AND UPPER(cr.title) LIKE UPPER('%%') " + + "AND nvl(cr.owner_id, cr.create_id) = au.user_id AND cr.rep_id = ra.rep_id (+) " + + " AND cr.folder_id= '" + folderId + "'" ;*/ + + /*String sql = "" + + "SELECT cr.rep_id, " + + "cr.rep_id report_id, " + + rep_title_sql + "||DECODE(cr.public_yn, 'Y', '', '" + PRIVATE_ICON + "')||cr.title||'' title, " + + "cr.descr, " + + "au.first_name||' '||au.last_name owner_name, " + + "TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + userID + + ", 'N', NVL(ra.read_only_yn, 'Y')) read_only_yn, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + userID + + ", 'Y', 'N') user_is_owner_yn " + + "FROM cr_report cr, " + + "app_user au, " + + "(SELECT rep_id, " + + "MIN(read_only_yn) read_only_yn " + + "FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = " + + userID + + ") " + + "UNION ALL " + + "(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN (" + + roleList.toString() + "))" + ") report_access " + "GROUP BY rep_id) ra " + + "WHERE " + "nvl(cr.owner_id, cr.create_id) = au.user_id " + + "AND cr.rep_id = ra.rep_id (+) AND cr.folder_id= '" + folderId + "'";*/ + + String sql = Globals.getLoadFolderReports(); + sql = sql.replace("[userID]", userID); + sql = sql.replace("[PRIVATE_ICON]", PRIVATE_ICON); + sql = sql.replace("[rep_title_sql]", rep_title_sql); + sql = sql.replace("[roleList.toString()]", roleList.toString()); + sql = sql.replace("[folderId]", folderId); + + + // String user_sql = " AND nvl(cr.owner_id, cr.create_id) = " + userID; + // String public_sql = " AND (nvl(cr.owner_id, cr.create_id) = " + userID + // + " OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL)"; + + String user_sql = Globals.getLoadFolderReportsUser(); + user_sql = user_sql.replace("[userID]", userID); + String public_sql = Globals.getLoadFolderReportsPublicSql(); + public_sql = public_sql.replace("[userID]", userID); + + if (isUserReport) + // My reports - user is owner + sql += user_sql; + else if (isPublicReport) + // Public reports - user has read or write access to the report + // (user is owner or report is public or user has explicit user or + // role access) + if (!AppUtils.isSuperUser(request)) + sql += public_sql; + else if (!AppUtils.isSuperUser(request)) + // All reports + // If user is super user - gets unrestricted access to all reports + // (read_only gets overriden later) + // else - not super user - doesn't get access to private reports of + // other users (= Public reports); Admin users get edit right + // override later + sql += public_sql; + logger.debug(EELFLoggerDelegate.debugLogger, ("query is for folder list is : " + sql)); + + DataSet ds = DbUtils.executeQuery(sql); + + /*Vector quickLinks = new Vector(ds.getRowCount()); + StringBuffer link = new StringBuffer(""); + for (int i = 0; i < ds.getRowCount(); i++) { + link = new StringBuffer(""); + link.append("" +ds.getString(i, 2) + "" + (Globals.getShowDescrAtRuntime() ? " - " + ds.getString(i, 2) : "") ); + quickLinks.add(link.toString()); + } + + return quickLinks;*/ + ReportSearchResult rsr = new ReportSearchResult(-1, ds.getRowCount(), 6, 7); + rsr.parseData(ds, request); + //rsr.truncateToPage(pageNo); + + return rsr; + } // loadFolderReports + + public static ArrayList loadQuickDownloadLinks(String userID, HttpServletRequest request) throws RaptorException { + /*String query = " SELECT a.file_name, b.title,to_char(a.dwnld_start_time, 'Dy DD-Mon-YYYY HH24:MI:SS') as time, "+ + " a.dwnld_start_time " + + " FROM cr_report_dwnld_log a, cr_report b where a.user_id = "+userID +" and "+ + " a.rep_id = b.rep_id " + + " and (a.dwnld_start_time) >= to_date(to_char(sysdate-24/24, 'mm/dd/yyyy'), 'mm/dd/yyyy') " + + " and a.record_ready_time is not null " + + " order by a.dwnld_start_time desc"; */ + + String query = Globals.getLoadQuickDownloadLinks(); + query = query.replace("[userID]", userID); + + + DataSet ds = DbUtils + .executeQuery(query); + ArrayList quickDownloadLinks = new ArrayList(ds.getRowCount()); + logger.debug(EELFLoggerDelegate.debugLogger, ("ROW SIZE " + ds.getRowCount())); + for (int i = 0; i < ds.getRowCount(); i++) { + quickDownloadLinks.add("" + ds.getString(i, 1)+ "" + " "+ ds.getString(i, 2)); + } + logger.debug(EELFLoggerDelegate.debugLogger, ("VECTOR SIZE " + quickDownloadLinks.size())); + + return quickDownloadLinks; + } // loadQuickLinks + + public static HashMap loadReportsToSchedule (HttpServletRequest request) throws RaptorException { + String userID = AppUtils.getUserID(request); + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + /*StringBuffer query = new StringBuffer(""); + query.append("SELECT cr.rep_id, "); + query.append("Initcap(cr.title), "); + query.append("cr.descr "); + query.append("FROM cr_report cr, "); + query.append("(SELECT rep_id, "); + query.append("MIN(read_only_yn) read_only_yn "); + query.append("FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = "); + query.append(userID); + query.append(") "); + query.append("UNION ALL "); + query.append("(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ("); + query.append(roleList.toString() + "))" + ") report_access "); + query.append("GROUP BY rep_id) ra " + "WHERE "); + query.append("cr.rep_id = ra.rep_id (+) AND "); + query.append(" (cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL or cr.owner_id = " + userID +") "); + query.append("ORDER BY Initcap(cr.title)") ;*/ + + String sql = Globals.getLoadReportsToSchedule(); + sql = sql.replace("[userID]", userID); + sql = sql.replace("[roleList.toString()]", roleList.toString()); + + // DataSet ds = DbUtils + // .executeQuery(query.toString()); + + DataSet ds = DbUtils + .executeQuery(sql); + HashMap map = new HashMap(); + for (int i = 0; i < ds.getRowCount(); i++) { + map.put(ds.getItem(i,0), ds.getItem(i,1)); + } + + return map; + } + + public static HashMap loadReportsToAddInDashboard (HttpServletRequest request) throws RaptorException { + String userID = AppUtils.getUserID(request); + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + /*StringBuffer query = new StringBuffer(""); + query.append("SELECT cr.rep_id, "); + query.append("cr.title, "); + query.append("cr.descr "); + query.append("FROM cr_report cr, "); + query.append("(SELECT rep_id, "); + query.append("MIN(read_only_yn) read_only_yn "); + query.append("FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = "); + query.append(userID); + query.append(") "); + query.append("UNION ALL "); + query.append("(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ("); + query.append(roleList.toString() + "))" + ") report_access "); + query.append("GROUP BY rep_id) ra " + "WHERE "); + query.append("cr.rep_id = ra.rep_id (+) AND "); + query.append("(nvl(cr.owner_id, cr.create_id) = " + userID); + query.append(" OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) "); + query.append(" AND (cr.dashboard_yn = 'N' or cr.dashboard_yn is null) "); + query.append("ORDER BY cr.title") ;*/ + + String sql = Globals.getLoadReportsToAddInDashboard(); + sql = sql.replace("[userID]", userID); + sql = sql.replace("[roleList.toString()]", roleList.toString()); + + // DataSet ds = DbUtils + // .executeQuery(query.toString()); + + DataSet ds = DbUtils + .executeQuery(sql); + + HashMap map = new HashMap(); + for (int i = 0; i < ds.getRowCount(); i++) { + map.put(ds.getItem(i,0), ds.getItem(i,1)); + } + + return map; + } + + public static Vector loadMyRecentLinks(String userID, HttpServletRequest request) throws RaptorException { + /* StringBuffer query = new StringBuffer(""); + query.append("select rep_id, title, descr, form_fields from ( select rownum, rep_id, title, descr, form_fields from "); + query.append(" (select cr.rep_id, cr.title, a.form_fields, cr.descr, a.log_time, a.user_id, a.action, a.action_value " ); + query.append(" from cr_report_log a, cr_report cr where user_id = " + userID); + query.append(" and action = 'Report Execution Time' and a.rep_id = cr.rep_id order by log_time desc) x where rownum <= 6 ) y where rownum >= 1");*/ +// DataSet ds = DbUtils +// .executeQuery( +// " SELECT a.file_name, b.title,to_char(a.dwnld_start_time, 'Dy DD-Mon-YYYY HH24:MI:SS') as time, "+ +// " a.dwnld_start_time " + +// " FROM cr_report_dwnld_log a, cr_report b where a.user_id = "+userID +" and "+ +// " a.rep_id = b.rep_id and (a.dwnld_start_time) >= to_date(to_char(sysdate-24/24, 'mm/dd/yyyy'), 'mm/dd/yyyy') " + +// " and a.record_ready_time is not null " + +// " order by a.dwnld_start_time desc"); +// DataSet ds = DbUtils + // .executeQuery(query.toString()); + + + String sql = Globals.getLoadMyRecentLinks(); + sql = sql.replace("[userID]", userID); + + DataSet ds = DbUtils + .executeQuery(sql); + + Vector myRecentLinks = new Vector(ds.getRowCount()); + logger.debug(EELFLoggerDelegate.debugLogger, ("ROW SIZE " + ds.getRowCount())); + for (int i = 0; i < ds.getRowCount(); i++) { + myRecentLinks.add("" + ds.getString(i, 1)+ ""); + } + logger.debug(EELFLoggerDelegate.debugLogger, ("VECTOR SIZE " + myRecentLinks.size())); + + return myRecentLinks; + } // loadQuickLinks + + public static void createReportLogEntry(Connection connection, String reportID, + String userID, String action, String executionTime,String form_fields) throws RaptorException { + if(form_fields.length()>=4000) form_fields = ""; + //String stmt = "INSERT INTO cr_report_log (rep_id, log_time, user_id, action, action_value, form_fields) VALUES(" + // + reportID + ", SYSDATE, " + userID + ", '" + action + "' , '" + executionTime + "', '"+ form_fields +"')"; + + String stmt = Globals.getCreateReportLogEntry(); + stmt = stmt.replace("[reportID]", reportID); + stmt = stmt.replace("[userID]", userID); + stmt = stmt.replace("[action]", action); + stmt = stmt.replace("[executionTime]", executionTime); + stmt = stmt.replace("[form_fields]", form_fields); + + if (Globals.getEnableReportLog()) + if (connection == null) + DbUtils.executeUpdate(stmt); + else + DbUtils.executeUpdate(connection, stmt); + } // createReportLogEntry + + public static void createReportLogEntryForExecutionTime(Connection connection, String reportID, + String userID, String executionTime, String action, String formFields) throws RaptorException { + if(formFields.length()>=4000) formFields = ""; + //String stmt = "INSERT INTO cr_report_log (rep_id, log_time, user_id, action, action_value, form_fields) VALUES(" + // + reportID + ", sysdate+1/(24*60*60) , " + userID + ", '" + action + "' , '" + executionTime + "', '"+ formFields +"')"; + + String stmt = Globals.getCreateReportLogEntryExecTime(); + stmt = stmt.replace("[reportID]", reportID); + stmt = stmt.replace("[userID]", userID); + stmt = stmt.replace("[action]", action); + stmt = stmt.replace("[executionTime]", executionTime); + stmt = stmt.replace("[formFields]", formFields); + + if (Globals.getEnableReportLog()) + if (connection == null) + DbUtils.executeUpdate(stmt); + else + DbUtils.executeUpdate(connection, stmt); + } // createReportLogEntry + + public static void clearReportLogEntries(String reportId, String userId) throws RaptorException { + String sql = Globals.getClearReportLogEntries(); + Connection connection = DbUtils.getConnection(); + PreparedStatement stmt = null; + String reportOwnerID = null; + int rowsAffected = 0; + try { + stmt = connection.prepareStatement(sql); + stmt.setInt(1, Integer.parseInt(reportId)); + stmt.setInt(2, Integer.parseInt(userId)); + rowsAffected = stmt.executeUpdate(); + if(rowsAffected > 0) connection.commit(); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } finally { + try { + stmt.close(); + connection.close(); + DbUtils.clearConnection(connection); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + } // clearReportLogEntries + + public static Vector loadReportLogEntries(String reportId) throws RaptorException { + /* StringBuffer query = new StringBuffer("SELECT x.log_time, x.user_id,") ; + query.append(" (CASE WHEN x.action = 'Report Execution Time' THEN "); + query.append(" ''||x.action||''"); + query.append(" ELSE x.action END) action, " ); + query.append(" (CASE WHEN x.action = 'Report Execution Time' THEN "); + query.append(" action_value " ); + query.append(" ELSE 'N/A' END) time_taken, " ); + query.append( " (CASE WHEN x.action = 'Report Execution Time' THEN '\"Run' ELSE 'N/A' END) run_image, " ); + query.append(" x.name FROM "); + query.append(" (SELECT rl.rep_id, TO_CHAR(rl.log_time, 'Month DD, YYYY HH:MI:SS AM') log_time, rl.action_value, fuser.last_name ||', '||fuser.first_name name, "); + query.append(" rl.user_id, rl.action, rl.form_fields FROM cr_report_log rl, fn_user fuser WHERE rl.rep_id = "+ nvls(reportId)+ " and rl.action != 'Report Run' and fuser.user_id = rl.user_id" ); + query.append(" ORDER BY rl.log_time DESC) x WHERE ROWNUM <= 100");*/ +// DataSet ds = DbUtils +// .executeQuery("SELECT x.log_time, x.user_id, x.action FROM (SELECT TO_CHAR(rl.log_time, 'Month DD, YYYY HH:MI:SS AM') log_time, rl.user_id, rl.action FROM cr_report_log rl WHERE rl.rep_id = " +// + nvls(reportId) + " ORDER BY rl.log_time DESC) x WHERE ROWNUM <= 100"); + // DataSet ds = DbUtils.executeQuery(query.toString()); + + String sql = Globals.getLoadReportLogEntries(); + sql = sql.replace("[AppUtils.getRaptorActionURL()]", AppUtils.getRaptorActionURL()); + sql = sql.replace("[AppUtils.getImgFolderURL()]", AppUtils.getImgFolderURL()); + sql = sql.replace("[nvls(reportId)]", nvls(reportId)); + + + DataSet ds = DbUtils.executeQuery(sql); + + Vector logEntries = new Vector(ds.getRowCount()); + + for (int i = 0; i < ds.getRowCount(); i++) + logEntries.add(new ReportLogEntry(ds.getString(i, 0), ds + .getString(i, 5), ds.getString(i, 2), ds.getString(i, 3), ds.getString(i, 4))); + + return logEntries; + } // loadReportLogEntries + + public static boolean doesUserCanScheduleReport(HttpServletRequest request, String scheduleId) throws RaptorException { + boolean flagLimit = false; + boolean flagScheduleIdPresent = false; + String userId = AppUtils.getUserID(request); + if(AppUtils.isAdminUser(request))return true; + //String query = "select crs.sched_user_id, count(*) from cr_report_schedule crs where sched_user_id = " + userId + " group by crs.sched_user_id having count(*) >= " + Globals.getScheduleLimit(); + String query = Globals.getDoesUserCanScheduleReport(); + query = query.replace("[userId]", userId); + query = query.replace("[Globals.getScheduleLimit()]", String.valueOf(Globals.getScheduleLimit())); + + DataSet ds = DbUtils.executeQuery(query); + logger.debug(EELFLoggerDelegate.debugLogger, (" User Schedule ds.getRowCount() " + ds.getRowCount() + " " +(ds.getRowCount()>0))); + if(ds.getRowCount() > 0) flagLimit = true; + else flagLimit = false; + logger.debug(EELFLoggerDelegate.debugLogger, ("scheduleId " + scheduleId)); + if(scheduleId==null || scheduleId.trim().length()<=0) return !flagLimit; + //query = "select crs.schedule_id from cr_report_schedule crs where schedule_id = " + scheduleId; + query = Globals.getDoesUserCanSchedule(); + query = query.replace("[scheduleId]", scheduleId); + + if(ds.getRowCount() > 0) flagScheduleIdPresent = true; + else flagScheduleIdPresent = false; + if(!flagLimit) return true; + if(flagLimit && flagScheduleIdPresent) return true; + else return false; + } + + public static String getSystemDateTime() throws RaptorException { + //String query = "select to_char(sysdate,'MM/dd/yyyy HH24:mi:ss') from dual"; + String query = Globals.getTheSystemDateTime(); + + DataSet ds = DbUtils.executeQuery(query); + String timeStr = ""; + if(ds.getRowCount() > 0) { + timeStr = ds.getString(0,0); + } + return timeStr; + + } + + public static String getNextDaySystemDateTime() throws RaptorException { + //String query = "select to_char(sysdate+1,'MM/dd/yyyy HH24:mi:ss') from dual"; + String query = Globals.getTheNextDayDateTime(); + DataSet ds = DbUtils.executeQuery(query); + String timeStr = ""; + if(ds.getRowCount() > 0) { + timeStr = ds.getString(0,0); + } + return timeStr; + + } + + public static String getNext15MinutesOfSystemDateTime() throws RaptorException { + //String query = "select to_char(sysdate+15/(24*60),'MM/dd/yyyy HH24:mi:ss') from dual"; + String query = Globals.getTheNextFifteenMinDateTime(); + + DataSet ds = DbUtils.executeQuery(query); + String timeStr = ""; + if(ds.getRowCount() > 0) { + timeStr = ds.getString(0,0); + } + return timeStr; + + } + + public static String getNext30MinutesOfSystemDateTime() throws RaptorException { + //String query = "select to_char(sysdate+30/(24*60),'MM/dd/yyyy HH24:mi:ss') from dual"; + String query = Globals.getTheNextThirtyMinDateTime(); + DataSet ds = DbUtils.executeQuery(query); + String timeStr = ""; + if(ds.getRowCount() > 0) { + timeStr = ds.getString(0,0); + } + return timeStr; + + } + + public static String getTemplateFile(String reportId) throws RaptorException { + //String query = "select template_file from cr_report_template_map where report_id = " + reportId; + String query = Globals.getTheTemplateFile(); + query = query.replace("[reportId]", reportId); + String templateFile = ""; + try { + DataSet ds = DbUtils.executeQuery(query); + if(ds.getRowCount() > 0) { + templateFile = ds.getString(0,0); + } + }catch(RaptorException ex) { + logger.debug(EELFLoggerDelegate.debugLogger, ("SQL Exception while trying to access cr_report_template_map ")); + } + return templateFile; + + } + + + public static HashMap loadPDFImgLookUp() throws RaptorException { + StringBuffer query = new StringBuffer(""); + HashMap pdfImgMap = new HashMap(); + //query.append("select image_id, image_loc from cr_raptor_pdf_img"); + query.append(Globals.getLoadPdfImgLookup()); + DataSet ds = DbUtils.executeQuery(query.toString()); + for (int i = 0; i < ds.getRowCount(); i++) { + pdfImgMap.put(ds.getString(i, 0), ds.getString(i,1)); + } + return pdfImgMap; + } // loadQuickLinks + + public static HashMap loadActionImgLookUp() throws RaptorException { + StringBuffer query = new StringBuffer(""); + HashMap pdfImgMap = new HashMap(); + //query.append("select image_id, image_loc from cr_raptor_action_img"); + query.append(Globals.getLoadActionImgLookup()); + DataSet ds = DbUtils.executeQuery(query.toString()); + for (int i = 0; i < ds.getRowCount(); i++) { + pdfImgMap.put(ds.getString(i, 0), ds.getString(i,1)); + } + return pdfImgMap; + } // loadQuickLinks + +} // ReportLoader + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/SearchHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/SearchHandler.java new file mode 100644 index 00000000..1a15e938 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/SearchHandler.java @@ -0,0 +1,479 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * SearchHandler.java - This class is used to search reports and sort them in different order + * based on preference. It can also download the list in CSV format. + * ------------------------------------------------------------------------------------------- + * + * + * + * Changes + * ------- + * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 13-Aug-2009 : Version 8.5 (Sundar);
  • Refresh is added while running report.
  • + *
+ * 27-Jul-2009 : Version 8.4 (Sundar);
  • A new sort order PUBLIC is added.
  • + *
  • In Public reports option it brings all the reports + * including the one which logged in user didn't create + * and which is not public. This is available for Super users and "Admin equivalent Super Users".
  • + *
+ * + */ +package org.openecomp.portalsdk.analytics.model; + +import java.io.*; +import java.sql.*; +import java.util.*; +import javax.servlet.http.*; + +import org.openecomp.portalsdk.analytics.controller.*; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.search.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class SearchHandler extends org.openecomp.portalsdk.analytics.RaptorObject { + private static final String HTML_FORM = "forma"; + private final static String PRIVATE_ICON = "Private "; + + public SearchHandler() { + } + + public void createCSVFileContent(Writer out, ReportSearchResult sr) throws IOException { + PrintWriter csvOut = new PrintWriter(out); + HtmlStripper strip = new HtmlStripper(); + + for (int c = 1; c < sr.getNumColumns(); c++) { + SearchResultColumn column = sr.getColumn(c); + if (column.getLinkURL() == null) + csvOut.print("\"" + column.getColumnTitle() + "\","); + } // for + csvOut.println(); + + for (int r = 0; r < sr.getNumRows(); r++) { + SearchResultRow row = sr.getRow(r); + + int c = 1; + for (row.resetNext(1); row.hasNext();) { + SearchResultField field = row.getNext(); + if (sr.getColumn(c++).getLinkURL() == null) + if (field.getDisplayValue().startsWith(PRIVATE_ICON)) + csvOut.print("\"" + + strip.stripHtml(field.getDisplayValue().substring(PRIVATE_ICON.length())) + + "\","); + else + csvOut.print("\"" + strip.stripHtml(field.getDisplayValue()) + "\","); + } // for + + csvOut.println(); + } // for + } // createCSVFileContent + + public String saveCSVPageFile(HttpServletRequest request, ReportSearchResult sr) { + try { + String csvFName = AppUtils.generateFileName(request, + (sr.getPageNo() < 0) ? AppConstants.FT_CSV_ALL : AppConstants.FT_CSV); + + BufferedWriter csvOut = new BufferedWriter(new FileWriter(AppUtils + .getTempFolderPath() + + csvFName)); + createCSVFileContent(csvOut, sr); + csvOut.close(); + + if (sr.getPageNo() < 0) + sr.setCsvAllRowsFileName(csvFName); + else + sr.setCsvPageFileName(csvFName); + + return csvFName; + } catch (Exception e) { + (new ErrorHandler()).processError(request, "Exception saving data to CSV file: " + + e.getMessage()); + return null; + } + } // saveCSVPageFile + + public ReportSearchResultJSON loadReportSearchResult(HttpServletRequest request) + throws RaptorException { + String userID = AppUtils.getUserID(request); + String fReportID = nvl(AppUtils.getRequestValue(request, AppConstants.RI_F_REPORT_ID)); + String fReportName = nvl(AppUtils.getRequestValue(request, + AppConstants.RI_F_REPORT_NAME)); + String sortOrder = nvl(AppUtils.getRequestValue(request, AppConstants.RI_SORT_ORDER), + AppConstants.RI_F_REPORT_NAME); + + String menuId = nvl(AppUtils.getRequestValue(request, AppConstants.RI_LIST_CATEGORY)); + + boolean userOnly = AppUtils.getRequestFlag(request, AppConstants.RI_USER_REPORTS); + boolean publicOnly = AppUtils.getRequestFlag(request, AppConstants.RI_PUBLIC_REPORTS); + boolean favoriteOnly = AppUtils.getRequestFlag(request, AppConstants.RI_FAVORITE_REPORTS); + + int pageNo = 0; + try { + pageNo = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE)); + } catch (Exception e) { + } + + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + String rep_title_sql = "''"; + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + // + /*String sql = "SELECT cr.rep_id, " + + "cr.rep_id report_id, " + + rep_title_sql+ + "||DECODE(cr.public_yn, 'Y', '', '" + + PRIVATE_ICON + + "')||cr.title||'' title, " + + "cr.descr, " + + "au.first_name||' '||au.last_name owner_name, " + + "TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + + userID + + ", 'N', NVL(ra.read_only_yn, 'Y')) read_only_yn, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + + userID + + ", 'Y', 'N') user_is_owner_yn, " + + "case when report_xml like '%N%' " + + "then 'N' " + + "when report_xml like '%Y%' " + + "or 1 = (select distinct 1 from cr_report_schedule where rep_id = cr.rep_id) " + + "then 'Y' " + + "else 'N' end " + + "FROM cr_report cr, " + + "app_user au, " + + "(SELECT rep_id, " + + "MIN(read_only_yn) read_only_yn " + + "FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = " + + userID + + ") " + + "UNION ALL " + + "(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN (" + + roleList.toString() + "))" + ") report_access " + "GROUP BY rep_id) ra " + + "WHERE TO_CHAR(cr.rep_id) = nvl('" + fReportID + + "', TO_CHAR(cr.rep_id)) AND " + "UPPER(cr.title) LIKE UPPER('%" + + fReportName + "%') AND " + "nvl(cr.owner_id, cr.create_id) = au.user_id " + + "AND cr.rep_id = ra.rep_id (+) ";*/ + + String sql = Globals.getLoadReportSearchResult(); + String rep_id = ""; + String rep_id_options = ""; + String rep_id_sql = Globals.getLoadReportSearchRepIdSql(); + //rep_id_sql = " AND ROUND(cr.rep_id, 0) like coalesce('%%', ROUND(cr.rep_id, 0)) "; + if(request.getParameter("rep_id")!=null) { + rep_id = request.getParameter("rep_id"); + } + if(request.getParameter("rep_id_options")!=null) { + rep_id_options = request.getParameter("rep_id_options"); + } + + /*Default: AND FORMAT(cr.rep_id, 0) like coalesce('%%', FORMAT(cr.rep_id, 0)) */ + + /*Equal to AND cr.rep_id = 1000 0 */ + /*Less than : AND cr.rep_id < 1000 1 */ + /*Greater than AND cr.rep_id > 1000 2 */ + + + if(AppUtils.nvl(rep_id).length()>0 ) { + if(AppUtils.nvl(rep_id_options).length()>0 ) { + switch (rep_id_options) { + case "0": + rep_id_sql = " AND cr.rep_id = "+ rep_id+" "; + break; + case "1": + rep_id_sql = " AND cr.rep_id < "+ rep_id+" "; + break; + case "2": + rep_id_sql = " AND cr.rep_id > "+ rep_id+" "; + break; + default: + rep_id_sql = Globals.getLoadReportSearchRepIdSql(); + break; + } + } else { + rep_id_sql = " AND cr.rep_id = "+ rep_id+" "; + } + } else { + rep_id_sql = Globals.getLoadReportSearchRepIdSql(); //equal is default + } + + sql = sql.replace("[fReportID]", rep_id_sql); + + String rep_name = ""; + String rep_name_options = ""; + String rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('%%') "; + if(request.getParameter("rep_name")!=null) { + rep_name = request.getParameter("rep_name"); + } + if(request.getParameter("rep_name_options")!=null) { + rep_name_options = request.getParameter("rep_name_options"); + } + + /* Report name AND UPPER(cr.title) LIKE UPPER('Dash%') 0 */ + + /* Report name AND UPPER(cr.title) LIKE UPPER('%1') 1 */ + /* Report name AND UPPER(cr.title) LIKE UPPER('%1%') 2 */ + + if(AppUtils.nvl(rep_name).length()>0 ) { + if(AppUtils.nvl(rep_name_options).length()>0 ) { + switch (rep_name_options) { + case "0": + rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('"+rep_name+"%') "; + break; + case "1": + rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('%"+rep_name+"') "; + break; + case "2": + rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('%"+rep_name+"%') "; + break; + default: + rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('%%') "; + break; + } + } else { + rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('%"+rep_name+"%') "; //contains is default + } + } else { + rep_name_sql = " AND UPPER(cr.title) LIKE UPPER('%%') "; + } + sql = sql.replace("[fReportName]", rep_name_sql); + + if (menuId.length() > 0){ + /*sql += "AND INSTR('|'||cr.menu_id||'|', '|'||'" + menuId + "'||'|') > 0 " + * +"AND + * cr.menu_approved_yn = + * 'Y' " + ;*/ + String sql_add = Globals.getLoadReportSearchInstr(); + sql+= sql_add; + } + + //String user_sql = " AND nvl(cr.owner_id, cr.create_id) = " + userID; + String user_sql = Globals.getLoadReportSearchResultUser(); + + //String public_sql = " AND (nvl(cr.owner_id, cr.create_id) = " + userID + // + " OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL)"; + String public_sql = Globals.getLoadReportSearchResultPublic(); + + //String fav_sql = " AND cr.rep_id in (select rep_id from cr_favorite_reports where user_id = " + userID +" ) "; + String fav_sql = Globals.getLoadReportSearchResultFav(); + + if (userOnly) + // My reports - user is owner + sql += " " + user_sql; + else if (publicOnly) { + // Public reports - user has read or write access to the report + // (user is owner or report is public or user has explicit user or + // role access) + if (!AppUtils.isSuperUser(request)) + sql += " " + public_sql; + } else if (favoriteOnly) { + sql += " " + public_sql; + sql += " " + fav_sql; + } else if (!AppUtils.isSuperUser(request)) { + // All reports + // If user is super user - gets unrestricted access to all reports + // (read_only gets overriden later) + // else - not super user - doesn't get access to private reports of + // other users (= Public reports); Admin users get edit right + // override later + //sql += public_sql; + sql += " " + public_sql; + } + + + + if (sortOrder.equals(AppConstants.RI_F_OWNER_ID)){ + //sql += " ORDER BY DECODE(nvl(cr.owner_id, cr.create_id), " + userID + //+ ", ' ', upper(au.first_name||' '||au.last_name)), upper(cr.title)"; + String sql_sort = Globals.getLoadReportSearchResultSort(); + sql+=" " + sql_sort; + } + else if (sortOrder.equals(AppConstants.RI_F_REPORT_ID)) + sql += " ORDER BY cr.rep_id"; + else if(sortOrder.equals(AppConstants.RI_F_REPORT_CREATE_DATE)) + sql += " ORDER BY cr.create_date"; + else if(sortOrder.equals(AppConstants.RI_F_PUBLIC)) + sql += " ORDER BY cr.public_yn desc"; + + else + // if(sortOrder.equals(AppConstants.RI_F_REPORT_NAME)) + sql += " ORDER BY upper(cr.title)"; + + sql = sql.replace("[rep_title_sql]", "cr.title"); + sql = sql.replace("[PRIVATE_ICON]", PRIVATE_ICON); + sql = sql.replace("[userID]", userID); + sql = sql.replace("[roleList.toString()]", roleList.toString()); + + //System.out.println("query is for search list is : " + sql); + DataSet ds = DbUtils.executeQuery(sql); + + ReportSearchResultJSON rsr = new ReportSearchResultJSON(0, 6, 7); + rsr.parseData(ds, request, 0, 20, 6, 7); + //saveCSVPageFile(request, rsr); + //rsr.truncateToPage(pageNo); + //saveCSVPageFile(request, rsr); + + return rsr; + } // loadReportSearchResult + + public ReportSearchResult loadFolderReportResult(HttpServletRequest request) + throws Exception { + String userID = AppUtils.getUserID(request); + String fReportID = nvl(AppUtils.getRequestValue(request, AppConstants.RI_F_REPORT_ID)); + String fReportName = nvl(AppUtils.getRequestValue(request, + AppConstants.RI_F_REPORT_NAME)); + String sortOrder = nvl(AppUtils.getRequestValue(request, AppConstants.RI_SORT_ORDER), + AppConstants.RI_F_REPORT_NAME); + + String menuId = nvl(AppUtils.getRequestValue(request, AppConstants.RI_LIST_CATEGORY)); + + boolean userOnly = AppUtils.getRequestFlag(request, AppConstants.RI_USER_REPORTS); + boolean publicOnly = AppUtils.getRequestFlag(request, AppConstants.RI_PUBLIC_REPORTS); + + int pageNo = 0; + try { + pageNo = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE)); + } catch (Exception e) { + } + + StringBuffer roleList = new StringBuffer(); + roleList.append("-1"); + String rep_title_sql = "''"; + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) + roleList.append("," + ((String) iter.next())); + // + /*String sql = "SELECT cr.rep_id, " + + "cr.rep_id report_id, " + + rep_title_sql+ + "||DECODE(cr.public_yn, 'Y', '', '" + + PRIVATE_ICON + + "')||cr.title||'' title, " + + "cr.descr, " + + "au.first_name||' '||au.last_name owner_name, " + + "TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + + userID + + ", 'N', NVL(ra.read_only_yn, 'Y')) read_only_yn, " + + "DECODE(NVL(cr.owner_id, cr.create_id), " + + userID + + ", 'Y', 'N') user_is_owner_yn " + + "FROM cr_report cr, " + + "app_user au, " + + "(SELECT rep_id, " + + "MIN(read_only_yn) read_only_yn " + + "FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = " + + userID + + ") " + + "UNION ALL " + + "(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN (" + + roleList.toString() + "))" + ") report_access " + "GROUP BY rep_id) ra " + + "WHERE TO_CHAR(cr.rep_id) = nvl('" + fReportID + + "', TO_CHAR(cr.rep_id)) AND " + "UPPER(cr.title) LIKE UPPER('%" + + fReportName + "%') AND " + "nvl(cr.owner_id, cr.create_id) = au.user_id " + + "AND cr.rep_id = ra.rep_id (+) ";*/ + + String sql = Globals.getLoadFolderReportResult(); + sql = sql.replace("[rep_title_sql]", rep_title_sql); + sql = sql.replace("[PRIVATE_ICON]", PRIVATE_ICON); + sql = sql.replace("[userID]", userID); + sql = sql.replace("[roleList.toString()]", roleList.toString()); + sql = sql.replace("[fReportID]", fReportID); + sql = sql.replace("[fReportName]", fReportName); + + if (menuId.length() > 0){ + /*sql += "AND INSTR('|'||cr.menu_id||'|', '|'||'" + menuId + "'||'|') > 0 " + * +"AND + * cr.menu_approved_yn = + * 'Y' " + ;*/ + String sql_add = Globals.getLoadReportSearchInstr(); + sql+= sql_add; + } + + //String user_sql = " AND nvl(cr.owner_id, cr.create_id) = " + userID; + String user_sql = Globals.getLoadReportSearchResultUser(); + + //String public_sql = " AND (nvl(cr.owner_id, cr.create_id) = " + userID + // + " OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL)"; + String public_sql = Globals.getLoadReportSearchResultPublic(); + + if (userOnly) + // My reports - user is owner + sql += user_sql; + else if (publicOnly) + // Public reports - user has read or write access to the report + // (user is owner or report is public or user has explicit user or + // role access) + if (!AppUtils.isSuperUser(request)) + sql += public_sql; + else if (!AppUtils.isSuperUser(request)) { + // All reports + // If user is super user - gets unrestricted access to all reports + // (read_only gets overriden later) + // else - not super user - doesn't get access to private reports of + // other users (= Public reports); Admin users get edit right + // override later + sql += public_sql; + } + + if (sortOrder.equals(AppConstants.RI_F_OWNER_ID)){ + + + //sql += " ORDER BY DECODE(nvl(cr.owner_id, cr.create_id), " + userID + // + ", ' ', au.first_name||' '||au.last_name), cr.title"; + + String sql_sort = Globals.getLoadFolderReportResultSort(); + sql+=sql_sort; + } + else if (sortOrder.equals(AppConstants.RI_F_REPORT_ID)) + sql += " ORDER BY cr.rep_id"; + else if(sortOrder.equals(AppConstants.RI_F_REPORT_CREATE_DATE)) + sql += " ORDER BY cr.create_date"; + else if(sortOrder.equals(AppConstants.RI_F_PUBLIC)) + sql += " ORDER BY cr.public_yn desc"; + else + // if(sortOrder.equals(AppConstants.RI_F_REPORT_NAME)) + sql += " ORDER BY cr.title"; + + //System.out.println("query is for search list is : " + sql); + DataSet ds = DbUtils.executeQuery(sql); + + ReportSearchResult rsr = new ReportSearchResult(-1, 6, 7); + rsr.parseData(ds, request); + saveCSVPageFile(request, rsr); + rsr.truncateToPage(pageNo); + saveCSVPageFile(request, rsr); + + return rsr; + } // loadFolderReportResult + + +} // SearchHandler diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ChartSeqComparator.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ChartSeqComparator.java new file mode 100644 index 00000000..7b15db55 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ChartSeqComparator.java @@ -0,0 +1,49 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.Comparator; + +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; + +public class ChartSeqComparator implements Comparator { + + public int compare(Object o1, Object o2) { + DataColumnType dct1 = (DataColumnType) o1; + DataColumnType dct2 = (DataColumnType) o2; + + int dct1ChartSeq = (dct1.getChartSeq()!=null ? dct1.getChartSeq().intValue(): -1); + int dct2ChartSeq = (dct2.getChartSeq()!=null ? dct2.getChartSeq().intValue(): -1); + + if (dct1ChartSeq == dct2ChartSeq) + return 0; + else if (dct1ChartSeq < 0) // Position columns + // with seq -1 at + // the end + return 1; + else if (dct2ChartSeq < 0) + return -1; + else if (dct1ChartSeq < dct2ChartSeq) + return -1; + else + return 1; + } // compare + +} // ChartSeqComparator diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameColLookup.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameColLookup.java new file mode 100644 index 00000000..96326639 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameColLookup.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.*; + +public class IdNameColLookup extends IdNameLookup { + private String colId = null; + + public IdNameColLookup(String colId, String dbTableName, String dbIdField, + String dbNameField, String dbSortByField) { + super(dbTableName, dbIdField, dbNameField, dbSortByField, false); + this.colId = colId; + } // IdNameColLookup + + public String getColId() { + return colId; + } + +} // IdNameColLookup diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameList.java new file mode 100644 index 00000000..3e6d6f42 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameList.java @@ -0,0 +1,183 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.system.*; + +public class IdNameList extends Vector { + protected int pageNo = -1; + + protected int pageSize = 50; + + private int nextElemIdx = 0; + + private String oldSql = null; + + public IdNameList() { + super(); + pageSize = Globals.getFormFieldsListSize(); + } // IdNameList + + public int getPageNo() { + return pageNo; + } // getPageNo + + public int getPageSize() { + return pageSize; + } // getPageSize + + public int getDataSize() { + return size(); + } // getDataSize + + public void resetNext() { + resetNext(0); + } // resetNext + + public void resetNext(int toPos) { + nextElemIdx = toPos; + } // resetNext + + public boolean hasNext() { + return (nextElemIdx < size()); + } // hasNext + + public IdNameValue getNext() { + return hasNext() ? getValue(nextElemIdx++) : null; + } // getNext + + public int getCount() { + return size(); + } // getCount + + public IdNameValue getValue(int idx) { + return (IdNameValue) get(idx); + } // getValue + + public void addValue(IdNameValue value) { + add(value); + } // addValue + + public void addValue(String id, String name, boolean defaultValue) { + addValue(new IdNameValue(id, name, defaultValue)); + } // addValue + + public void addValue(String id, String name, boolean defaultValue, boolean readOnly) { + addValue(new IdNameValue(id, name, defaultValue, readOnly)); + } // addValue + + public void addValue(String id, String name) { + addValue(new IdNameValue(id, name)); + } // addValue + + public void addValue(int idx, IdNameValue value) { + add(idx, value); + } // addValue + + public void addValue(int idx, String id, String name) { + addValue(idx, new IdNameValue(id, name)); + } // addValue + + public String getNameById(String id) { + for (int i = 0; i < size(); i++) { + IdNameValue value = getValue(i); + if (value.getId().equals(id)) + return value.getName(); + } // for + + return null; + } // getNameById + + public String getIdByName(String name) { + for (int i = 0; i < size(); i++) { + IdNameValue value = getValue(i); + if (value.getName().equals(name)) + return value.getId(); + } // for + + return null; + } // getIdByName + + public boolean canUseSearchString() { + return true; + } + + public String getBaseSQL() { + return null; + } + + public String getOldSql() { + return oldSql; + } + + public void setOldSql(String oldSql) { + this.oldSql = oldSql; + } + public String getBaseWholeSQL() { + return null; + } + + public String getBaseWholeReadonlySQL() { + return null; + } + + public String getBaseSQLForPDFExcel(boolean multiParam) { + return null; + } + + public void clearData() { + } + + public void loadData(String pageNo, String searchString, String dbInfo,String userId) throws RaptorException {} + public void loadUserData(String pageNo, String searchString, String dbInfo,String userId) throws RaptorException {} + public void loadUserData(int pageNo, String searchString, String dbInfo, String userId) throws RaptorException {} + public void loadUserData(String searchString, int pageNo, String dbInfo) throws RaptorException {} + + public void loadData(String pageNo) throws RaptorException {} + public void loadData(int pageNo) throws RaptorException {} + public void loadData(String pageNo, String searchString, String dbInfo) throws RaptorException {} + private void loadData(int pageNo, String searchString, String dbInfo) throws RaptorException {} + +/* + public void loadData(int pageNo, String dbInfo) throws RaptorException { + } + + public void loadUserData(int pageNo, String dbInfo, String userId) throws RaptorException { + } + + + + + public void loadData(String pageNo, String searchString) throws RaptorException { + } + +*/ + protected static String nvl(String s) { + return (s == null) ? "" : s; + } + + protected static String nvl(String s, String sDefault) { + return nvl(s).equals("") ? sDefault : s; + } + +} // IdNameList diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameLookup.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameLookup.java new file mode 100644 index 00000000..73f65c89 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameLookup.java @@ -0,0 +1,204 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.*; +import org.openecomp.portalsdk.analytics.model.runtime.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; + +public class IdNameLookup extends IdNameSql { + private String dbTableName = null; + + private String dbIdField = null; + + private String dbNameField = null; + + private String dbSortByField = null; + + private String searchString = ""; + + public IdNameLookup(int pageNo, String dbTableName, String dbIdField, String dbNameField) { + this(dbTableName, dbIdField, dbNameField); + + this.pageNo = pageNo; + } // IdNameLookup + + public IdNameLookup(String dbTableName, String dbIdField, String dbNameField) { + this(dbTableName, dbIdField, dbNameField, null, "", false); + } // IdNameLookup + +/* public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, + String dbSortByField) { + super(); + + setDbTableName(dbTableName); + setDbIdField(dbIdField); + setDbNameField(dbNameField); + setDbSortByField(dbSortByField); + updateParentSQL(); + } // IdNameLookup + + public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, + String dbSortByField, String defaultSQL) { + super(); + + setDbTableName(dbTableName); + setDbIdField(dbIdField); + setDbNameField(dbNameField); + setDbSortByField(dbSortByField); + setDefaultSQL(defaultSQL); + updateParentSQL(); + } // IdNameLookup +*/ + public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, + String dbSortByField, boolean textField) { + super(); + setDbTableName(dbTableName); + setDbIdField(dbIdField); + setDbNameField(dbNameField); + setDbSortByField(dbSortByField); + if(!textField) + updateParentSQL(); + } // IdNameLookup + + public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, + String dbSortByField, String defaultSQL, boolean textField) { + super(); + + setDbTableName(dbTableName); + setDbIdField(dbIdField); + setDbNameField(dbNameField); + setDbSortByField(dbSortByField); + setDefaultSQL(defaultSQL); + if(!textField) + updateParentSQL(); + } // IdNameLookup + + public String getDbTableName() { + return dbTableName; + } + + public String getDbIdField() { + return dbIdField; + } + + public String getDbNameField() { + return dbNameField; + } + + public String getDbSortByField() { + return dbSortByField; + } + + public void setDbTableName(String dbTableName) { + this.dbTableName = dbTableName; + } + + public void setDbIdField(String dbIdField) { + this.dbIdField = dbIdField; + } + + public void setDbNameField(String dbNameField) { + this.dbNameField = dbNameField; + } + + + public void setDbSortByField(String dbSortByField) { + this.dbSortByField = dbSortByField; + } + + private void updateParentSQL() { + String sql_start = "SELECT DISTINCT " + dbIdField + " id, " + dbNameField + " name"; + String sql_end = " FROM " + dbTableName + " WHERE " + dbIdField + " IS NOT NULL"; + if (searchString.length() > 0) + sql_end += " AND UPPER(" + dbNameField + ") LIKE UPPER('" + searchString + "')"; + + String sql_middle = ""; + if (dbSortByField != null && (!dbSortByField.equals(dbNameField)) && (!dbSortByField.trim().startsWith("TO_DATE"))) + sql_middle = ", " + + ((dbSortByField.indexOf(' ') > 0) ? dbSortByField.substring(0, + dbSortByField.indexOf(' ')) : dbSortByField) + " sort"; + + setSqlNoOrderBy(sql_start + sql_middle + sql_end); +// System.out.println("SQL Start " + sql_start); +// System.out.println("SQL Middle " + sql_middle); +// System.out.println("SQL End " + sql_end); +// System.out.println("DbSortByField " + dbSortByField); + + setSql(sql_start + sql_middle + sql_end + " ORDER BY " + nvl(dbSortByField, "2")); + } // updateParentSQL + + public boolean canUseSearchString() { + return true; + } + + public String getBaseSQL() { + return "SELECT " + dbIdField + " FROM " + dbTableName; + } // getBaseSQL + + public String getBaseWholeSQL() { + return "SELECT " + dbIdField + " FROM " + dbTableName; + } // getBaseSQL + + /* + public void loadData(int pageNo) throws RaptorException { + loadData(pageNo, ""); + } // loadData + + public void loadData(String pageNo) throws RaptorException { + loadData(pageNo, ""); + } // loadData +*/ + + public void loadData(String pageNo, String searchString, String dbInfo) throws RaptorException { + int iPageNo = 0; + + if (pageNo != null) + try { + iPageNo = Integer.parseInt(pageNo); + } catch (NumberFormatException e) { + } + + loadData(iPageNo, searchString, dbInfo); + } // loadData + + private void loadData(int pageNo, String searchString, String dbInfo) throws RaptorException { + boolean dataAlreadyLoaded = (this.pageNo == pageNo) + && (this.searchString.equals(searchString)); + + if (dataAlreadyLoaded) + return; + + if (!this.searchString.equals(searchString)) { + dataSize = -1; + pageNo = 0; + } // if + + this.pageNo = pageNo; + this.searchString = searchString; + updateParentSQL(); + performLoadData(searchString,dbInfo); + } // loadData + +} // IdNameLookup diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameSql.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameSql.java new file mode 100644 index 00000000..602025fe --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameSql.java @@ -0,0 +1,400 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * IdNameSql.java - This class is used to generate form field items when sql is provided. + * ------------------------------------------------------------------------------------------- + * + * Created By : Stan Pishamanov + * Modified By: Sundar Ramalingam + * + * Changes + * ------- + * 08-Jun-2009 : Version 8.3 (RS); Rownum references is avoided for reports connnecting to Daytona + * Database. + * + */ +package org.openecomp.portalsdk.analytics.model.base; + +import java.util.*; + +import org.openecomp.portalsdk.analytics.controller.ActionHandler; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.*; +import org.openecomp.portalsdk.analytics.model.runtime.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class IdNameSql extends IdNameList { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(IdNameSql.class); + + + protected int dataSize = -1; + + protected int dataSizeUsedInPopup = -1; + + private String sql = null; + + private String oldSql = null; + + private String defaultSQL = null; + + private String sqlNoOrderBy = null; + + public IdNameSql(int pageNo, String sql, String defaultSQL) { + this(sql,defaultSQL); + this.pageNo = pageNo; + } // IdNameSql + + public IdNameSql(String sql) { + this(); + setSql(sql); + } // IdNameSql + + public IdNameSql(String sql, String defaultSQL) { + this(); + setDefaultSQL(defaultSQL); + setSql(sql); + } // IdNameSql + + protected IdNameSql() { + super(); + } // IdNameSql + + public boolean canUseSearchString() { + return true; + } + + public String getSql() { + return sql; + } + + public String getOldSql() { + return oldSql; + } + + public String getBaseSQL() { + return "SELECT id FROM (" + sql + ") xid"; + } + + public String getBaseWholeSQL() { + return "SELECT id, name FROM (" + sql + ") xid"; + } + + public String getBaseWholeReadonlySQL() { + return "SELECT id, name, ff_readonly FROM (" + sql + ") xid"; + } + + public String getBaseSQLForPDFExcel(boolean multiParam) { + if(!multiParam) + return "SELECT id, name FROM (" + sql + ") xid where id = '[VALUE]'"; + else + return "SELECT id, name FROM (" + sql + ") xid where id in [VALUE]"; + + } + + // public String getSqlNoOrderBy() { return sqlNoOrderBy; } + + protected void setSql(String sql) { + this.sql = sql; + } + + public void setOldSql(String oldSql) { + this.oldSql = oldSql; + } + + protected void setSqlNoOrderBy(String sql) { + this.sqlNoOrderBy = sql; + } + + public int getDataSize() { + return dataSize; + } // getDataSize + + public int getDataSizeUsedinPopup() { + return dataSizeUsedInPopup; + } // getDataSizeUsedinPopup + + public void setDataSizeUsedinPopup(int dataSizePop) { + this.dataSizeUsedInPopup = dataSizePop; + } // getDataSizeUsedinPopup + + public void clearData() { + removeAllElements(); + } // clearData + +/* public void loadData(String pageNo, String searchString, String dbInfo, String userId) throws RaptorException { + // setSql(searchString); + loadUserData(pageNo, searchString, dbInfo,userId); + } // loadData +*/ + + public void loadUserData(String pageNo, String searchString, String dbInfo,String userId) throws RaptorException { + int iPageNo = 0; + + if (pageNo != null) + try { + iPageNo = Integer.parseInt(pageNo); + } catch (NumberFormatException e) { + } + + loadUserData(iPageNo, searchString, dbInfo,userId); + } // loadData + + public void loadUserData(int pageNo, String searchString, String dbInfo, String userId) throws RaptorException { + if(userId!=null) { + String sql = Utils.replaceInString(getSql(), "[LOGGED_USERID]", userId); + //String defaultSQL = ""; + if(defaultSQL!=null && (defaultSQL.trim().toLowerCase().startsWith("select")) ) { + defaultSQL = Utils.replaceInString(getDefaultSQL(), "[LOGGED_USERID]", userId); + setDefaultSQL(defaultSQL); + } + setSql(sql); + + } + loadData(searchString,pageNo, dbInfo); + } + + public void loadData(String searchString, int pageNo, String dbInfo) throws RaptorException { + + //boolean dataAlreadyLoaded = (this.pageNo == pageNo); + + //if (dataAlreadyLoaded) + // return; + + this.pageNo = pageNo; + + performLoadData(searchString, dbInfo); + } // loadData + + protected void performLoadData(String searchString, String dbInfo) throws RaptorException { + long currentTime = System.currentTimeMillis(); + int startRow = 0; + int endRow = dataSize; + String readOnlyInSql = "ff_readonly"; + String dbType = Globals.getDBType(); + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + if (pageNo >= 0) { + startRow = pageNo * pageSize; + endRow = startRow + pageSize; + } // if + DataSet ds = null; + DataSet dsDefault = null; + StringBuffer query = new StringBuffer(""); + StringBuffer queryPop = new StringBuffer(""); + String sql = getSql(); + boolean avail_ReadOnly = (sql.toLowerCase().indexOf(readOnlyInSql)!=-1); + + if (dbType.equals("DAYTONA") && getSql().trim().toUpperCase().startsWith("SELECT")) { + query.append(getSql()); + } else { + if(avail_ReadOnly) // need to add readonlyinsql + if(!(Globals.isMySQL() && dbType.equals(AppConstants.MYSQL))) + query.append("SELECT rownum, id, name, " + readOnlyInSql +" FROM ("+ Globals.getReportSqlForFormfield() +", " + readOnlyInSql + " FROM (" + sql + + ") x "+ Globals.getReportSqlForFormfieldSuffix()); + else + query.append("SELECT id, name, " + readOnlyInSql +" FROM ("+ Globals.getReportSqlForFormfield() +", " + readOnlyInSql + " FROM (" + sql + + ") x "+ Globals.getReportSqlForFormfieldSuffix()); + else + query.append(Globals.getReportSqlForFormfieldPrefix()+ Globals.getReportSqlForFormfield() +" FROM (" + sql + + ") x " + Globals.getReportSqlForFormfieldSuffix()); + if(pageNo!= -2 && (dbType.equals(AppConstants.ORACLE)) ) { + query.append(" WHERE rownum <= " + ((dataSize < 0) ? (endRow + 1) : endRow)); + } else if(pageNo!=2 && (dbType.equals(AppConstants.POSTGRESQL))) { + query.append(" LIMIT " + ((dataSize < 0) ? (endRow + 1) : endRow)); + + } else if(pageNo!=2 && (dbType.equals(AppConstants.MYSQL))) { + query.append(" LIMIT " + startRow); //((dataSize < 0) ? (endRow + 1) : endRow) + + } + if(searchString!=null && searchString.length()>0 && !searchString.equals("%")) { + if(pageNo == -2) query.append(" WHERE "); + else query.append(" and "); + query.append("name like '"+ searchString +"'"); + } + if(dbType.equals(AppConstants.POSTGRESQL)) { + query.append(") xx OFFSET " + startRow); + } else if(dbType.equals(AppConstants.MYSQL)) { + query.append(" ," + ((dataSize < 0) ? (endRow + 1) : endRow) +") xx"); + } else if(dbType.equals(AppConstants.ORACLE)) + query.append(") xx WHERE rownum>" + startRow); + } + String defaultQuery =""; + boolean readOnly = true; + ds = ConnectionUtils.getDataSet(query.toString(), dbInfo); + + // if ( (dbInfo!=null) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + // Globals.getRDbUtils().setDBPrefix(dbInfo); + // ds = RemDbUtils.executeQuery(query); + // } + // else + // ds = DbUtils.executeQuery(query); + clearData(); + if (dbType.equals("DAYTONA") && (getDefaultSQL()!=null && getDefaultSQL().trim().toUpperCase().startsWith("SELECT"))) { + defaultQuery = getDefaultSQL(); + } else if (getDefaultSQL()!=null && getDefaultSQL().length()>10 && getDefaultSQL().substring(0,10).toLowerCase().startsWith("select")) { + defaultQuery = Globals.getReportSqlForFormfieldPrefix()+ Globals.getReportSqlForFormfield() +" FROM (" + getDefaultSQL() + + ") x " + + ") xx "; + logger.debug(EELFLoggerDelegate.debugLogger, ("Default Query " +defaultQuery)); + } + HashMap defaultMap = new HashMap(); + if(!isNull(defaultQuery)) { + dsDefault = ConnectionUtils.getDataSet(defaultQuery, dbInfo); + if(dsDefault!=null && dsDefault.getRowCount()>0) { + for (int i = 0; i < dsDefault.getRowCount(); i++) { + //addValue(dsDefault.getString(i, 0), dsDefault.getString(i, 1), true); + defaultMap.put(dsDefault.getString(i, "id"), dsDefault.getString(i, "name")); + } + } + } + + for (int i = 0; i < ((pageNo!=-2)?Math.min(ds.getRowCount(), pageSize):ds.getRowCount()); i++) { + //if(getCount()==0) + // addValue(ds.getString(i, 0), ds.getString(i, 1)); + if(i==0 && avail_ReadOnly) + readOnly = ds.getString(i, "ff_readonly").toUpperCase().startsWith("Y")||ds.getString(i, "ff_readonly").toUpperCase().startsWith("T"); + if(getCount()>=0) {//&& !((IdNameValue)getValue(0)).getId().equals(ds.getString(i, 0))) + if(defaultMap.get(ds.getString(i, "id")) == null) + if(avail_ReadOnly) + addValue(ds.getString(i, "id"), ds.getString(i, "name"), false, readOnly); + else + addValue(ds.getString(i, "id"), ds.getString(i, "name"), false); + else + if(avail_ReadOnly) + addValue(ds.getString(i, "id"), ds.getString(i, "name"), true, readOnly); + else + addValue(ds.getString(i, "id"), ds.getString(i, "name"), true); + } + } + + if (!(dbType.equals("DAYTONA"))) { + if (ds.getRowCount() <= pageSize) { + if(dsDefault!=null && dsDefault.getRowCount()>0) + dataSize = ds.getRowCount()+1; + else + dataSize = ds.getRowCount(); + + //System.out.println("IDNAME SQL COUNT");*/ + if(searchString!=null && searchString.length()>0 && !searchString.equals("%")) { + queryPop = new StringBuffer(""); + queryPop.append("SELECT count(*) num_rows FROM ("+ Globals.getReportSqlForFormfield() +", name FROM (" + sql + + ") x "); + if(searchString!=null && searchString.length()>0 && !searchString.equals("%")) + queryPop.append(" where name like '"+ searchString +"'"); + queryPop.append(") xx "); + + ds = ConnectionUtils.getDataSet(queryPop.toString(), dbInfo); + try { + dataSizeUsedInPopup = Integer.parseInt(ds.getString(0, 0)); + } catch (NumberFormatException e) { + } + } else if(dataSizeUsedInPopup == -3) { + queryPop = new StringBuffer(""); + //System.out.println("IDNAME SQL COUNT"); + //queryPop.append("SELECT count(*) num_rows FROM ("+query.toString()+") x"); + queryPop.append("SELECT count(*) num_rows FROM ("+ Globals.getReportSqlForFormfield() +", name FROM (" + sql + + ") x "); + queryPop.append(") xx "); + + ds = ConnectionUtils.getDataSet(queryPop.toString(), dbInfo); + // if ( (dbInfo!=null) && + // (!dbInfo.equals(AppConstants.DB_LOCAL))) { + // Globals.getRDbUtils().setDBPrefix(dbInfo); + // ds = RemDbUtils.executeQuery(query); + // } + // else + // ds = DbUtils.executeQuery(query); + // + try { + dataSizeUsedInPopup = Integer.parseInt(ds.getString(0, 0)); + } catch (NumberFormatException e) { + } + + } + + } else { + //pageNo = 0; + if(pageNo!= -2) { + queryPop = new StringBuffer(""); + //System.out.println("IDNAME SQL COUNT"); + //queryPop.append("SELECT count(*) num_rows FROM ("+query.toString()+") x"); + queryPop.append("SELECT count(*) num_rows FROM ("+ Globals.getReportSqlForFormfield() +" FROM (" + sql + + ") x "); + queryPop.append(") xx "); + + ds = ConnectionUtils.getDataSet(queryPop.toString(), dbInfo); + // if ( (dbInfo!=null) && + // (!dbInfo.equals(AppConstants.DB_LOCAL))) { + // Globals.getRDbUtils().setDBPrefix(dbInfo); + // ds = RemDbUtils.executeQuery(query); + // } + // else + // ds = DbUtils.executeQuery(query); + // + try { + dataSize = Integer.parseInt(ds.getString(0, 0)); + dataSizeUsedInPopup = Integer.parseInt(ds.getString(0, 0)); + } catch (NumberFormatException e) { + } + } + } // else + } // dataSize < 0 + long totalTime = System.currentTimeMillis() - currentTime; + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken to the above formfield Query (+ count Query if any) --- " + totalTime)); + } // performLoadData + + + public String getDefaultSQL() { + + return defaultSQL; + } + + + public void setDefaultSQL(String defaultSQL) { + + this.defaultSQL = defaultSQL; + } + + public void setSQL(String sql_) + { + this.sql = sql_; + } + + public static boolean isNull(String a) { + if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null")) + return true; + else + return false; + } +} // IdNameSql diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameValue.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameValue.java new file mode 100644 index 00000000..763a44c0 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/IdNameValue.java @@ -0,0 +1,100 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +public class IdNameValue { + private String id = null; + + private String name = null; + + private boolean defaultValue = false; + + private boolean readOnly = false; + + public IdNameValue() { + super(); + } + + public IdNameValue(String id, String name) { + this(); + + setId(id); + setName(name); + setDefaultValue(false); + + } // IdNameValue + + public IdNameValue(String id, String name, boolean defaultValue) { + this(); + + setId(id); + setName(name); + setDefaultValue(defaultValue); + } // IdNameValue + + public IdNameValue(String id, String name, boolean defaultValue, boolean readOnly) { + this(); + + setId(id); + setName(name); + setDefaultValue(defaultValue); + setReadOnly(readOnly); + } // IdNameValue + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(boolean defaultValue) { + this.defaultValue = defaultValue; + } + + /** + * @return the visibility + */ + public boolean isReadOnly() { + return readOnly; + } + + /** + * @param readOnly the value to set + */ + public void setReadOnly(boolean readOnly) { + this.readOnly = readOnly; + } + + +} // IdNameValue diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/NameComparator.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/NameComparator.java new file mode 100644 index 00000000..4ccff331 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/NameComparator.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.Comparator; + +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; + +public class NameComparator implements Comparator { + + public int compare(Object o1, Object o2) { + return ((IdNameValue) o1).getName() + .compareToIgnoreCase((((IdNameValue) o2).getName())); + } // compare + +} // NameComparator + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderBySeqComparator.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderBySeqComparator.java new file mode 100644 index 00000000..930f508c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderBySeqComparator.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.Comparator; + +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; + +public class OrderBySeqComparator implements Comparator { + + public int compare(Object o1, Object o2) { + if (((DataColumnType) o1).getOrderBySeq() == ((DataColumnType) o2).getOrderBySeq()) + return 0; + else if (((DataColumnType) o1).getOrderBySeq() < ((DataColumnType) o2).getOrderBySeq()) + return -1; + else + return 1; + } // compare + +} // OrderSeqComparator diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderSeqComparator.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderSeqComparator.java new file mode 100644 index 00000000..e6c013dc --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/OrderSeqComparator.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.util.Comparator; + +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; + +public class OrderSeqComparator implements Comparator { + + public int compare(Object o1, Object o2) { + if (((DataColumnType) o1).getOrderSeq() == ((DataColumnType) o2).getOrderSeq()) + return 0; + else if (((DataColumnType) o1).getOrderSeq() < ((DataColumnType) o2).getOrderSeq()) + return -1; + else + return 1; + } // compare + +} // OrderSeqComparator diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportSecurity.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportSecurity.java new file mode 100644 index 00000000..40a3f266 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportSecurity.java @@ -0,0 +1,404 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.io.*; +import java.sql.*; +import java.util.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.analytics.controller.ActionHandler; +import org.openecomp.portalsdk.analytics.error.*; +import org.openecomp.portalsdk.analytics.model.base.*; +import org.openecomp.portalsdk.analytics.model.definition.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class ReportSecurity extends org.openecomp.portalsdk.analytics.RaptorObject { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportSecurity.class); + + + private String reportID = null; + + private String ownerID = null; + + private String createID = null; + + private String createDate = null; + + private String updateID = null; + + private String updateDate = null; + + private boolean isPublic = false; + + private Hashtable reportRoles = new Hashtable(); + + private Hashtable reportUsers = new Hashtable(); + + public ReportSecurity(String reportID) { + this(reportID, null, null, null, null, null, false); + } // ReportSecurity + + public ReportSecurity(String reportID, String ownerID, String createID, String createDate, + String updateID, String updateDate, boolean isPublic) { + super(); + + if (ownerID == null) + // Need to load the report record from the database + if (!reportID.equals("-1")) + try { + /*DataSet ds = DbUtils + .executeQuery("SELECT NVL(cr.owner_id, cr.create_id) owner_id, cr.create_id, TO_CHAR(cr.create_date, '" + + Globals.getOracleTimeFormat() + + "') create_date, maint_id, TO_CHAR(cr.maint_date, '" + + Globals.getOracleTimeFormat() + + "') update_date, cr.public_yn FROM cr_report cr WHERE cr.rep_id=" + + reportID);*/ + String sql = Globals.getReportSecurity(); + sql = sql.replace("[rw.getReportID()]", reportID); + DataSet ds = DbUtils.executeQuery(sql); + ownerID = ds.getString(0, 0); + createID = ds.getString(0, 1); + createDate = ds.getString(0, 2); + updateID = ds.getString(0, 3); + updateDate = ds.getString(0, 4); + isPublic = nvl(ds.getString(0, 5)).equals("Y"); + } catch (Exception e) { + String eMsg = "ReportSecurity.ReportSecurity: Unable to load report record details. Exception: " + + e.getMessage(); + //Log.write(eMsg); + logger.debug(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] "+eMsg)); + throw new RuntimeException(eMsg); + } + + this.reportID = reportID; + this.ownerID = ownerID; + this.createID = createID; + this.createDate = createDate; + this.updateID = updateID; + this.updateDate = updateDate; + this.isPublic = isPublic; + + /* + * reportUsers.put(ownerID, "N"); // Owner has full access + * reportRoles.put(AppUtils.getSuperRoleID(), "N"); // Super role has + * full access for(Iterator iter=AppUtils.getAdminRoleIDs().iterator(); + * iter.hasNext(); ) reportRoles.put((String) iter.next(), "Y"); // + * Admin role(s) have read-only access + */ + try { + String reportUserAccessSql= Globals.getReportUserAccess(); + reportUserAccessSql = reportUserAccessSql.replace("[reportID]", reportID); + + DataSet ds = DbUtils + .executeQuery(reportUserAccessSql); + for (int i = 0; i < ds.getRowCount(); i++) { + String roleID = nvl(ds.getString(i, 0)); + if (roleID.length() > 0) + reportRoles.put(roleID, ds.getString(i, 2)); + + String userID = nvl(ds.getString(i, 1)); + if (userID.length() > 0) + reportUsers.put(userID, ds.getString(i, 2)); + } // for + } catch (Exception e) { + String eMsg = "ReportSecurity.ReportSecurity: Unable to load access priviledges - error " + + e.getMessage(); + logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg)); + throw new RuntimeException(eMsg); + } + } // ReportSecurity + + public String getOwnerID() { + return ownerID; + } + + public String getCreateID() { + return createID; + } + + public String getCreateDate() { + return createDate; + } + + public String getUpdateID() { + return updateID; + } + + public String getUpdateDate() { + return updateDate; + } + + public void setOwnerID(String ownerID) { + this.ownerID = ownerID; + } + + public void setPublic(boolean isPublic) { + this.isPublic = isPublic; + } + + public void reportCreate(String reportID, String userID, boolean isPublic) { + this.reportID = reportID; + this.ownerID = userID; + this.createID = userID; + this.createDate = Utils.getCurrentDateTime(); + this.updateID = userID; + this.updateDate = this.createDate; + this.isPublic = isPublic; + } // reportCreate + + public void reportUpdate(HttpServletRequest request) throws RaptorException { + checkUserWriteAccess(request); + String userID = AppUtils.getUserID(request); + this.updateID = userID; + this.updateDate = Utils.getCurrentDateTime(); + } // reportUpdate + + /** ************************************************************* */ + + public Vector getReportUsers(HttpServletRequest request) throws RaptorException { + HttpSession session = request.getSession(); + String query = Globals.getCustomizedScheduleQueryForUsers(); + String[] sessionParameters = Globals.getSessionParams().split(","); + session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request)); + String param = ""; + for (int i = 0; i < sessionParameters.length; i++) { + param = (String)session.getAttribute(sessionParameters[0]); + query = Utils.replaceInString(query, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + } + boolean isAdmin = AppUtils.isAdminUser(request); + Vector allUsers = AppUtils.getAllUsers(query,param, isAdmin); + Vector rUsers = new Vector(allUsers.size()); + + for (Iterator iter = allUsers.iterator(); iter.hasNext();) { + IdNameValue user = (IdNameValue) iter.next(); + String readOnlyAccess = (String) reportUsers.get(user.getId()); + if (readOnlyAccess != null) + rUsers.add(new SecurityEntry(user.getId(), user.getName(), readOnlyAccess + .equals("Y"))); + } // for + + return rUsers; + } // getReportUsers + + public Vector getReportRoles(HttpServletRequest request) throws RaptorException { + HttpSession session = request.getSession(); + String query = Globals.getCustomizedScheduleQueryForRoles(); + String[] sessionParameters = Globals.getSessionParams().split(","); + String param = ""; + for (int i = 0; i < sessionParameters.length; i++) { + param = (String)session.getAttribute(sessionParameters[0]); + query = Utils.replaceInString(query, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + + } + boolean isAdmin = AppUtils.isAdminUser(request); + Vector allRoles = AppUtils.getAllRoles(query, param, isAdmin); + Vector rRoles = new Vector(allRoles.size()); + + for (Iterator iter = allRoles.iterator(); iter.hasNext();) { + IdNameValue role = (IdNameValue) iter.next(); + String readOnlyAccess = (String) reportRoles.get(role.getId()); + if (readOnlyAccess != null) + rRoles.add(new SecurityEntry(role.getId(), role.getName(), readOnlyAccess + .equals("Y"))); + } // for + + return rRoles; + } // getReportRoles + + /** ************************************************************* */ + + private void validateReadOnlyAccess(String readOnlyAccess) throws Exception { + if (!(readOnlyAccess != null && (readOnlyAccess.equals("Y") || readOnlyAccess + .equals("N")))) + throw new RuntimeException( + "[ReportSecurity.validateReadOnlyAccess] Invalid parameter value"); + } // validateReadOnlyAccess + + public void addUserAccess(String userID, String readOnlyAccess) throws Exception { + validateReadOnlyAccess(readOnlyAccess); + reportUsers.put(userID, readOnlyAccess); + String addUserAccessSql= Globals.getAddUserAccess(); + addUserAccessSql = addUserAccessSql.replace("[reportID]", reportID); + addUserAccessSql = addUserAccessSql.replace("[userID]", userID); + addUserAccessSql = addUserAccessSql.replace("[readOnlyAccess]", readOnlyAccess); + DbUtils + .executeUpdate(addUserAccessSql); + } // addUserAccess + + public void updateUserAccess(String userID, String readOnlyAccess) throws Exception { + validateReadOnlyAccess(readOnlyAccess); + reportUsers.remove(userID); + reportUsers.put(userID, readOnlyAccess); + String updateUserAccessSql= Globals.getUpdateUserAccess(); + updateUserAccessSql = updateUserAccessSql.replace("[reportID]", reportID); + updateUserAccessSql = updateUserAccessSql.replace("[userID]", userID); + updateUserAccessSql = updateUserAccessSql.replace("[readOnlyAccess]", readOnlyAccess); + DbUtils.executeUpdate(updateUserAccessSql); + } // updateUserAccess + + public void removeUserAccess(String userID) throws Exception { + reportUsers.remove(userID); + + String removeUserAccessSql= Globals.getRemoveUserAccess(); + removeUserAccessSql = removeUserAccessSql.replace("[reportID]", reportID); + removeUserAccessSql = removeUserAccessSql.replace("[userID]", userID); + DbUtils.executeUpdate(removeUserAccessSql); + } // removeUserAccess + + public void addRoleAccess(String roleID, String readOnlyAccess) throws Exception { + validateReadOnlyAccess(readOnlyAccess); + reportRoles.put(roleID, readOnlyAccess); + String addRoleAccessSql= Globals.getAddRoleAccess(); + addRoleAccessSql = addRoleAccessSql.replace("[reportID]", reportID); + addRoleAccessSql = addRoleAccessSql.replace("[roleID]", roleID); + addRoleAccessSql = addRoleAccessSql.replace("[readOnlyAccess]", readOnlyAccess); + DbUtils + .executeUpdate(addRoleAccessSql); + } // addRoleAccess + + public void updateRoleAccess(String roleID, String readOnlyAccess) throws Exception { + validateReadOnlyAccess(readOnlyAccess); + reportRoles.remove(roleID); + reportRoles.put(roleID, readOnlyAccess); + String updateRoleAccessSql= Globals.getUpdateRoleAccess(); + updateRoleAccessSql = updateRoleAccessSql.replace("[reportID]", reportID); + updateRoleAccessSql = updateRoleAccessSql.replace("[roleID]", roleID); + updateRoleAccessSql = updateRoleAccessSql.replace("[readOnlyAccess]", readOnlyAccess); + DbUtils.executeUpdate(updateRoleAccessSql); + } // updateRoleAccess + + public void removeRoleAccess(String roleID) throws Exception { + reportRoles.remove(roleID); + String removeRoleAccessSql= Globals.getRemoveRoleAccess(); + removeRoleAccessSql = removeRoleAccessSql.replace("[reportID]", reportID); + removeRoleAccessSql = removeRoleAccessSql.replace("[roleID]", roleID); + DbUtils.executeUpdate(removeRoleAccessSql); + } // removeRoleAccess + + /** ************************************************************* */ + + public void checkUserReadAccess(HttpServletRequest request, String userID) throws RaptorException { + if(userID == null) + userID = AppUtils.getUserID(request); + if(userID != null) { + //userID = AppUtils.getUserID(request); + if (nvl(reportID).equals("-1")) + return; + + if (true) //todo: replace with proper check isPublic + return; + + if (userID.equals(ownerID)) + return; + + if (reportUsers.get(userID) != null) + return; + } + Vector userRoles = null; + String userName = null; + if(userID == null) { + userRoles = AppUtils.getUserRoles(request); + userName = AppUtils.getUserName(request); + userID = AppUtils.getUserID(request); + } else { + userRoles = AppUtils.getUserRoles(userID); + userName = AppUtils.getUserName(userID); + } + if (nvl(reportID).equals("-1")) + return; + + if (isPublic) + return; + + if (userID.equals(ownerID)) + return; + + if (reportUsers.get(userID) != null) + return; + + for (Iterator iter = userRoles.iterator(); iter.hasNext();) { + String userRole = (String) iter.next(); + if (nvl(userRole).equals(AppUtils.getSuperRoleID())) + return; + } + for (Iterator iter = userRoles.iterator(); iter.hasNext();) { + String userRole = (String) iter.next(); + + if (nvl(userRole).equals(AppUtils.getSuperRoleID())) + return; + + if (reportRoles.get(userRole) != null) + return; + + for (Iterator iterA = AppUtils.getAdminRoleIDs().iterator(); iterA.hasNext();) + if (nvl(userRole).equals((String) iterA.next())) + return; + } // for + + throw new UserAccessException(reportID, "[" + userID + "] " + + userName, AppConstants.UA_READ); + } // checkUserReadAccess + + public void checkUserWriteAccess(HttpServletRequest request) throws RaptorException { + String userID = AppUtils.getUserID(request); + if (nvl(reportID).equals("-1")) + return; + + if (userID.equals(ownerID)) + return; + + if (nvl((String) reportUsers.get(userID)).equals("N")) + return; + + for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();) { + String userRole = (String) iter.next(); + + if (nvl(userRole).equals(AppUtils.getSuperRoleID())) + return; + + if (nvl((String) reportRoles.get(userRole)).equals("N")) + return; + + for (Iterator iterA = AppUtils.getAdminRoleIDs().iterator(); iterA.hasNext();) + if (nvl(userRole).equals((String) iterA.next())) + return; + } // for + + throw new UserAccessException(reportID, "[" + userID + "] " + + AppUtils.getUserName(request), AppConstants.UA_WRITE); + } // checkUserWriteAccess + + public void checkUserDeleteAccess(HttpServletRequest request) throws RaptorException { + String userID = AppUtils.getUserID(request); + if (Globals.getDeleteOnlyByOwner()) { + if (!userID.equals(ownerID)) + throw new UserAccessException(reportID, "[" + userID + "] " + + AppUtils.getUserName(request), AppConstants.UA_DELETE); + } else + checkUserWriteAccess(request); + } // checkUserDeleteAccess + +} // ReportSecurity diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportWrapper.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportWrapper.java new file mode 100644 index 00000000..1638a396 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/base/ReportWrapper.java @@ -0,0 +1,5719 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.base; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TreeSet; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.transform.stream.StreamResult; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException; +import org.openecomp.portalsdk.analytics.error.UserDefinedException; +import org.openecomp.portalsdk.analytics.model.DataCache; +import org.openecomp.portalsdk.analytics.model.ReportLoader; +import org.openecomp.portalsdk.analytics.model.definition.TableSource; +import org.openecomp.portalsdk.analytics.model.runtime.FormField; +import org.openecomp.portalsdk.analytics.model.runtime.ReportParamValues; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.system.DbUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.SQLCorrector; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.xmlobj.ChartAdditionalOptions; +import org.openecomp.portalsdk.analytics.xmlobj.ChartDrillFormfield; +import org.openecomp.portalsdk.analytics.xmlobj.ChartDrillOptions; +import org.openecomp.portalsdk.analytics.xmlobj.ColFilterList; +import org.openecomp.portalsdk.analytics.xmlobj.ColFilterType; +import org.openecomp.portalsdk.analytics.xmlobj.CustomReportType; +import org.openecomp.portalsdk.analytics.xmlobj.DashboardEditorList; +import org.openecomp.portalsdk.analytics.xmlobj.DashboardReports; +import org.openecomp.portalsdk.analytics.xmlobj.DashboardReportsNew; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnList; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.DataSourceList; +import org.openecomp.portalsdk.analytics.xmlobj.DataSourceType; +import org.openecomp.portalsdk.analytics.xmlobj.DataminingOptions; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldList; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.analytics.xmlobj.FormatList; +import org.openecomp.portalsdk.analytics.xmlobj.FormatType; +import org.openecomp.portalsdk.analytics.xmlobj.JavascriptItemType; +import org.openecomp.portalsdk.analytics.xmlobj.JavascriptList; +import org.openecomp.portalsdk.analytics.xmlobj.Marker; +import org.openecomp.portalsdk.analytics.xmlobj.ObjectFactory; +import org.openecomp.portalsdk.analytics.xmlobj.PDFAdditionalOptions; +import org.openecomp.portalsdk.analytics.xmlobj.PredefinedValueList; +import org.openecomp.portalsdk.analytics.xmlobj.ReportMap; +import org.openecomp.portalsdk.analytics.xmlobj.Reports; +import org.openecomp.portalsdk.analytics.xmlobj.SemaphoreList; +import org.openecomp.portalsdk.analytics.xmlobj.SemaphoreType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +/**
+ * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting)
+ *
+ * + * --------------------------------------------------------------------------------------------------
+ * ReportWrapper.java - This is the base class for the RAPTOR. This involves in creating,
+ * modifying, running RAPTOR reports.
+ * --------------------------------------------------------------------------------------------------
+ * + * + * Change Log

+ * + * 31-Aug-2009 : Version 8.5.1 (Sundar);
  • All the elements in the meta xml is copied to the target reports.
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 27-Jul-2009 : Version 8.4 (Sundar);
  • verifySQLBasedReportAccess method checks for Admin user instead of super user.
+ * 09-Jul-2009 : Version 8.4 (Sundar);
  • Bug due to parsing and removing formfields from "and" is bulletproofed to the right "and" to which the formfield is associated.
+ * 08-Jul-2009 : Version 8.4 (Sundar);
  • Bug due to parsing and removing formfields when there is no parameter for Daytona specific database is resolved.
+ * 29-Jun-2009 : Version 8.4 (Sundar);
  • isLastSeriesALineChart() and setLastSeriesALineChart(String value) method have been added for the Bar Chart enhancements.
+ * 23-Jun-2009 : Version 8.4 (Sundar);
  • check for cr.getChartAdditionalOptions() for null value is added.
+ * 22-Jun-2009 : Version 8.4 (Sundar);
  • Wrapper functions to call JAXB were added. These Wrapper + * functions are related to the Pareto chart, Time Difference Chart, Multiple Pie Chart and generic Chart Options.
+ * + */ + +public class ReportWrapper extends org.openecomp.portalsdk.analytics.RaptorObject { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportWrapper.class); + + + protected CustomReportType cr = null; + + protected Vector allColumns = null; + + protected Vector allVisibleColumns = null; + + protected Vector allFilters = null; + + protected String generatedSQL = null; + + protected String generatedChartSQL = null; + + protected String wholeSQL = null; // For display purposes only + + + protected String reportID = null; + + protected String menuID = ""; + + protected boolean menuApproved = false; + + protected String reportDefType = ""; + + protected ReportSecurity reportSecurity = null; + + protected String reportSQLWithRowNum = null; + + protected String reportSQLOnlyFirstPart = null; + + + private ReportWrapper(CustomReportType cr, String reportID, ReportSecurity reportSecurity) { + super(); + + if (reportID == null) + reportID = "-1"; + + this.cr = cr; + this.reportID = reportID; + + this.reportSecurity = reportSecurity; + } // ReportWrapper + + public ReportWrapper(ReportWrapper rw) { + this(rw.getCustomReport(), // .cloneCustomReport() + rw.getReportID(), rw.reportSecurity); + + this.menuID = rw.getMenuID(); + this.menuApproved = rw.isMenuApproved(); + + this.reportDefType = rw.getReportDefType(); + } // ReportWrapper + + public ReportWrapper(CustomReportType cr, String reportID, String ownerID, String createID, + String createDate, String updateID, String updateDate, String menuID, + boolean menuApproved) throws RaptorException { + this(cr, reportID, null); + + if (ownerID == null) + // Need to load the report record from the database + if (!reportID.equals("-1")) + try { + /*DataSet ds = DbUtils + .executeQuery("SELECT NVL(cr.owner_id, cr.create_id) owner_id, cr.create_id, TO_CHAR(cr.create_date, '" + + Globals.getOracleTimeFormat() + + "') create_date, maint_id, TO_CHAR(cr.maint_date, '" + + Globals.getOracleTimeFormat() + + "') update_date, cr.menu_id, cr.menu_approved_yn FROM cr_report cr WHERE cr.rep_id=" + + reportID);*/ + + String r_sql = Globals.getReportWrapperFormat(); + r_sql = r_sql.replace("[Globals.getTimeFormat()]", Globals.getTimeFormat()); + r_sql = r_sql.replace("[reportID]", reportID); + + DataSet ds = DbUtils + .executeQuery(r_sql); + + ownerID = ds.getString(0, 0); + createID = ds.getString(0, 1); + createDate = ds.getString(0, 2); + updateID = ds.getString(0, 3); + updateDate = ds.getString(0, 4); + menuID = nvl(ds.getString(0, 5)); + menuApproved = nvl(ds.getString(0, 6)).equals("Y"); + } catch (Exception e) { + String eMsg = "ReportWrapper.ReportWrapper: Unable to load report record details. Exception: " + + e.getMessage(); + //Log.write(eMsg); + logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] "+ eMsg)); + throw new RaptorRuntimeException(eMsg); + } + + this.menuID = nvl(menuID); + this.menuApproved = menuApproved; + + if (!reportID.equals("-1")) + updateReportDefType(); + + reportSecurity = new ReportSecurity(reportID, ownerID, createID, createDate, updateID, + updateDate, cr.isPublic()); + } // ReportWrapper + + public CustomReportType getCustomReport() { + return cr; + } + + public String getReportID() { + return reportID; + } + + public String getMenuID() { + return menuID; + } + + public boolean checkMenuIDSelected(String chkMenuID) { + return ("|" + menuID + "|").indexOf("|" + chkMenuID + "|") >= 0; + } + + public boolean isMenuApproved() { + return menuApproved; + } + + public String getReportDefType() { + return reportDefType; + } + + public void setMenuID(String menuID) { + this.menuID = menuID; + } + + public void setMenuApproved(boolean menuApproved) { + this.menuApproved = menuApproved; + } + + public void setReportDefType(String reportDefType) { + this.reportDefType = reportDefType; + } + + public void updateReportDefType() { + this.reportDefType = (nvl(cr.getReportSQL()).length() > 0) ? ((cr.getDataminingOptions()!=null && nvl(cr.getDataminingOptions().getClassifier()).length()>0) ? + AppConstants.RD_SQL_BASED_DATAMIN:AppConstants.RD_SQL_BASED) + : AppConstants.RD_VISUAL; + } + + public String getJavascriptElement() { + return cr.getJavascriptElement(); + } + + public int getPageSize() { + return cr.getPageSize()==null?50:cr.getPageSize(); + } + + public int getMaxRowsInExcelDownload() { + return cr.getMaxRowsInExcelDownload()==null?500:cr.getMaxRowsInExcelDownload(); + } + + public boolean isDisplayFolderTree() { + return cr.isDisplayFolderTree()!=null?cr.isDisplayFolderTree().booleanValue():false; + } + + public boolean isHideFormFieldAfterRun() { + return cr.isHideFormFieldAfterRun()!=null?cr.isHideFormFieldAfterRun().booleanValue():false; + } + + public void setHideFormFieldAfterRun(boolean hideFormFieldAfterRun) { + cr.setHideFormFieldAfterRun(hideFormFieldAfterRun); + } + + public boolean isReportInNewWindow() { + return cr.isReportInNewWindow()!=null?cr.isReportInNewWindow().booleanValue():false; + } + + public String getReportType() { + return cr.getReportType(); + } + + public String getReportName() { + return cr.getReportName(); + } + + public String getDBInfo() { + return cr.getDbInfo(); + } + + public String getDBType() { + return cr.getDbType(); + } + + public boolean isDrillDownURLInPopupPresent() { + return cr.isDrillURLInPoPUpPresent()!=null?cr.isDrillURLInPoPUpPresent().booleanValue():false; + } + + public void setDrillDownURLInPopupPresent(boolean value) { + cr.setDrillURLInPoPUpPresent(value); + } + + public String getReportDescr() { + return cr.getReportDescr(); + } + + public String getChartType() { + return cr.getChartType(); + } + + public boolean displayChartTitle() { + return cr.isShowChartTitle(); + } + + public void setShowChartTitle(boolean showTitle) { + cr.setShowChartTitle(showTitle); + } + + + public String getChartTypeFixed() { + return cr.getChartTypeFixed(); + } + + public boolean isChartTypeFixed() { + return nvl(cr.getChartTypeFixed()).length() > 0 ? cr.getChartTypeFixed().equals("Y") + : (!Globals.getAllowRuntimeChartSel()); + } + + public String getChartLeftAxisLabel() { + return cr.getChartLeftAxisLabel(); + } + + public String getChartRightAxisLabel() { + return cr.getChartRightAxisLabel(); + } + + public String getChartWidth() { + return cr.getChartWidth(); + } + + public int getChartWidthAsInt() { + return getIntValue(cr.getChartWidth(), Globals.getDefaultChartWidth()); + } + + public String getChartHeight() { + return cr.getChartHeight()==null?"500":cr.getChartHeight(); + } + + /*public boolean isChartMultiSeries() { + //String s = cr.getChartMultiSeries(); + return + return (nvl(s).length()>0)? (s.equals("Y")||s.equals("y")||s.equalsIgnoreCase("true")?true:false):true; + }*/ + + public boolean displayPieOrderinRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartMultiplePieOrder():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + } + + public boolean isMultiplePieOrderByRow() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartMultiplePieOrder():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return (nvl(s).length()>0)? (s.equals("row")?true:false):true; + } + + public boolean isMultiplePieOrderByColumn() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartMultiplePieOrder():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return (nvl(s).length()>0)&&(s.equals("column"))?true:false; + } + + public boolean displayPieLabelDisplayinRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + } + + public String getMultiplePieLabelDisplay() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return s; + } + + public boolean displayChartDisplayinRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartDisplay():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + } + + public boolean isChartDisplayIn3D() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartDisplay():""; + if(nvl(s).length()<=0) return true; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return (nvl(s).length()>0)&&(s.equals("3D"))?true:false; + } + + public boolean displayChartOrientationInRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartOrientation():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + + } + + public String getLinearRegression() { + String s = ""; + s = nvl((cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLinearRegression():"Y"); + return s; + } + + public void setLinearRegression(String linear) { + cr.getChartAdditionalOptions().setLinearRegression(linear); + } + + public String getLinearRegressionColor() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLinearRegressionColor():""; + } + + public String getCustomizedRegressionPoint() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getMaxRegression():""; + } + + public void setCustomizedRegressionPoint( String d) { + cr.getChartAdditionalOptions().setMaxRegression(d); + } + + public void setLinearRegressionColor(String color) { + cr.getChartAdditionalOptions().setLinearRegressionColor(color); + } + + public String getExponentialRegressionColor() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getExponentialRegressionColor():""; + } + + public void setExponentialRegressionColor(String color) { + cr.getChartAdditionalOptions().setExponentialRegressionColor(color); + } + + public void setRangeAxisUpperLimit(String d) { + if(cr.getChartAdditionalOptions()!=null) + cr.getChartAdditionalOptions().setRangeAxisUpperLimit(d); + } + + public void setRangeAxisLowerLimit(String d) { + if(cr.getChartAdditionalOptions()!=null) + cr.getChartAdditionalOptions().setRangeAxisLowerLimit(d); + } + + public String getRangeAxisUpperLimit() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getRangeAxisUpperLimit():""; + } + + public String getRangeAxisLowerLimit() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getRangeAxisLowerLimit():""; + } + + public boolean isChartAnimate() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isAnimate()!=null?cr.getChartAdditionalOptions().isAnimate():false):false; + } + + public boolean isAnimateAnimatedChart() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isAnimateAnimatedChart()!=null?cr.getChartAdditionalOptions().isAnimateAnimatedChart():false):true; + } + + public void setAnimateAnimatedChart(boolean animate) { + cr.getChartAdditionalOptions().setAnimateAnimatedChart(animate); + } + + public void setChartStacked(boolean stacked) { + cr.getChartAdditionalOptions().setStacked(stacked); + } + + public boolean isChartStacked() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isStacked()!=null?cr.getChartAdditionalOptions().isStacked():true):false; + } + + public void setBarControls(boolean barControls) { + cr.getChartAdditionalOptions().setBarControls(barControls); + } + + public boolean displayBarControls() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isBarControls()!=null?cr.getChartAdditionalOptions().isBarControls():false):false; + } + + public void setXAxisDateType(boolean dateType) { + cr.getChartAdditionalOptions().setXAxisDateType(dateType); + } + + public boolean isXAxisDateType() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isXAxisDateType()!=null?cr.getChartAdditionalOptions().isXAxisDateType():false):false; + } + + public void setLessXaxisTickers(boolean lessTickers) { + cr.getChartAdditionalOptions().setLessXaxisTickers(lessTickers); + } + + public boolean isLessXaxisTickers() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isLessXaxisTickers()!=null?cr.getChartAdditionalOptions().isLessXaxisTickers():false):false; + } + + public void setTimeAxis(boolean timeAxis) { + cr.getChartAdditionalOptions().setTimeAxis(timeAxis); + } + + public boolean isTimeAxis() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isTimeAxis()!=null?cr.getChartAdditionalOptions().isTimeAxis():true):true; + } + + public void setLogScale(boolean logScale) { + cr.getChartAdditionalOptions().setLogScale(logScale); + } + + public boolean isLogScale() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isLogScale()!=null?cr.getChartAdditionalOptions().isLogScale():false):false; + } + + + public void setMultiSeries(boolean multiSeries) { + cr.getChartAdditionalOptions().setMultiSeries(multiSeries); + cr.setChartMultiSeries(multiSeries?"Y":"N"); + } + + public boolean isMultiSeries() { + if(AppUtils.nvl(cr.getChartMultiSeries()).equals("Y")) + cr.getChartAdditionalOptions().setMultiSeries(true); + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isMultiSeries()!=null?cr.getChartAdditionalOptions().isMultiSeries():false):false; + } + + public void setTimeSeriesRender(String timeSeriesRenderer) { + cr.getChartAdditionalOptions().setTimeSeriesRender(timeSeriesRenderer); + } + + public String getTimeSeriesRender() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getTimeSeriesRender():"line"; + } + + public void setShowXAxisLabel(boolean showXaxisLabel) { + cr.getChartAdditionalOptions().setShowXAxisLabel(showXaxisLabel); + } + + public boolean isShowXaxisLabel() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isShowXAxisLabel()!=null?cr.getChartAdditionalOptions().isShowXAxisLabel():false):false; + } + + public void setAddXAxisTickers(boolean addXAxisTickers) { + cr.getChartAdditionalOptions().setAddXAxisTickers(addXAxisTickers); + } + + public boolean isAddXAxisTickers() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().isAddXAxisTickers()!=null?cr.getChartAdditionalOptions().isAddXAxisTickers():false):true; + } + + public void setZoomIn(Integer zoomIn) { + cr.getChartAdditionalOptions().setZoomIn(zoomIn); + } + + public Integer getZoomIn() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().getZoomIn()!=null?cr.getChartAdditionalOptions().getZoomIn():new Integer("25")): new Integer("25"); + } + + public void setTimeAxisType(String timeAxisType) { + cr.getChartAdditionalOptions().setTimeAxisType(timeAxisType); + } + + public String getTimeAxisType() { + return (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().getTimeAxisType()!=null?cr.getChartAdditionalOptions().getTimeAxisType():"hourly"): "hourly"; + } + + public void setTopMargin(Integer topMargin) { + cr.getChartAdditionalOptions().setTopMargin(topMargin); + } + + public Integer getTopMargin() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getTopMargin(): new Integer("30"); + } + + public void setBottomMargin(Integer bottomMargin) { + cr.getChartAdditionalOptions().setBottomMargin(bottomMargin); + } + + public Integer getBottomMargin() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getBottomMargin(): new Integer("50"); + } + + public void setRightMargin(Integer rightMargin) { + cr.getChartAdditionalOptions().setRightMargin(rightMargin); + } + + public Integer getRightMargin() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getRightMargin(): new Integer("60"); + } + + public void setLeftMargin(Integer leftMargin) { + cr.getChartAdditionalOptions().setLeftMargin(leftMargin); + } + + public Integer getLeftMargin() { + return (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLeftMargin(): new Integer("100"); + } + + + public boolean isVerticalOrientation() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartOrientation():""; + if(nvl(s).length()<=0) return true; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return (nvl(s).length()>0)&&(s.equals("vertical"))?true:false; + } + + public boolean isHorizontalOrientation() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getChartOrientation():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return (nvl(s).length()>0)&&(s.equals("horizontal"))?true:false; + } + + public boolean displaySecondaryChartRendererInRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getSecondaryChartRenderer():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + + } + + public String getSecondaryChartRenderer() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getSecondaryChartRenderer():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return s; + } + + public String getOverlayItemValueOnStackBar() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getOverlayItemValueOnStackBar():"N"; + return s; + } + + public boolean displayIntervalInputInRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getIntervalFromdate():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + } + + public boolean showLegendDisplayOptionsInRunPage() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getHidechartLegend():""; + if(nvl(s).indexOf("|")!= -1) { + s = s.substring(s.indexOf("|")+1); + return getFlagInBoolean(s); + } else return false; + } + + public String getIntervalFromdate() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getIntervalFromdate():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return nvl(s,""); + } + + public String getIntervalTodate() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getIntervalTodate():""; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return nvl(s,""); + } + + public String getIntervalLabel() { + return cr.getChartAdditionalOptions()!=null ? nvl(cr.getChartAdditionalOptions().getIntervalLabel()):""; + } + + public String getLegendPosition() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLegendPosition():""; + return nvl(s,"bottom"); + } + + public String getLegendLabelAngle() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLabelAngle():""; + return nvl(s,"UP90"); + } + + public String getMaxLabelsInDomainAxis() { + String s = ""; + s = (cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getMaxLabelsInDomainAxis():""; + return nvl(s,"99"); + } + + public boolean isLastSeriesALineChart() { + String s = ""; + s = nvl((cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLastSeriesALineChart():""); + return s.equals("Y"); + } + + public boolean isLastSeriesABarChart() { + String s = ""; + s = nvl((cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getLastSeriesABarChart():""); + return s.equals("Y"); + } + + public void setChartLegendDisplay(String value) { + cr.getChartAdditionalOptions().setHidechartLegend(value); + } + + public boolean hideChartLegend() { + String s = ""; + s = nvl((cr.getChartAdditionalOptions()!=null)?cr.getChartAdditionalOptions().getHidechartLegend():"N"); + if(nvl(s).length()<=0) s = "N"; + if(nvl(s).indexOf("|")!= -1) s = s.substring(0, s.indexOf("|")); + return s.equals("Y"); + } + + public void setChartToolTips(String value) { + cr.getChartAdditionalOptions().setHideToolTips(value); + } + + public void setDomainAxisValuesAsString(String value) { + cr.getChartAdditionalOptions().setKeepDomainAxisValueAsString(value); + } + + public boolean hideChartToolTips() { + boolean s = true; + s = (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().getHideToolTips()!=null? + (cr.getChartAdditionalOptions().getHideToolTips().equals("Y")?true:false):(Globals.hideToolTipsGlobally()?true:false)):(Globals.hideToolTipsGlobally()?true:false); + return s; + } + + public boolean keepDomainAxisValueInChartAsString() { + boolean s = true; + s = (cr.getChartAdditionalOptions()!=null)?(cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString()!=null? + (cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString().equals("Y")?true:false):false):false; + return s; + } + + public int getChartHeightAsInt() { + return getIntValue(cr.getChartHeight(), Globals.getDefaultChartHeight()); + } + + public boolean isPublic() { + return cr.isPublic(); + } + + public boolean isDashboardType() throws RaptorException { + return cr.isDashboardType()!=null?cr.isDashboardType().booleanValue():false; + } + + // public String getCreateId() { return cr.getCreateId(); } + // public Calendar getCreateDate() { return cr.getCreateDate(); } + public String getReportSQL() { + return cr.getReportSQL(); + } + + public String getReportTitle() { + return cr.getReportTitle(); + } + + public String getReportSubTitle() { + return cr.getReportSubTitle(); + } + + public String getReportHeader() { + return cr.getReportHeader(); + } + + public String getReportFooter() { + return cr.getReportFooter(); + } + + public String getNumDashCols() { + return cr.getNumDashCols(); + } + + public int getNumDashColsAsInt() { + return getIntValue(cr.getNumDashCols(), 1); + } + + public String getNumFormCols() { + return cr.getNumFormCols(); + } + + public int getNumFormColsAsInt() { + return getIntValue(cr.getNumFormCols(), 5); + } + + public String getDisplayOptions() { + return cr.getDisplayOptions(); + } + + + +//Additional Methods + + public int getJumpTo() { + return cr.getJumpTo()==null?1:cr.getJumpTo(); + } + public void setJumpTo(int value){ + cr.setJumpTo(value); + } + + + public int getSearchPageSize(){ + return cr.getSearchPageSize()==null?20:cr.getSearchPageSize(); + } + public void setSearchPageSize(int value){ + cr.setSearchPageSize(value); + } + + + public boolean isToggleLayout(){ + if(cr.isToggleLayout()!=null) + return cr.isToggleLayout(); + + else + return Globals.displayRuntimeOptionsAsDefault(); + + } + public void setToggleLayout(boolean value){ + cr.setToggleLayout(value); + } + + public boolean isShowPageSize(){ + if(cr.isShowPageSize()!=null) + return cr.isShowPageSize(); + + else + return Globals.displayRuntimeOptionsAsDefault(); + + } + public void setShowPageSize(boolean value){ + cr.setShowPageSize(value); + } + + public boolean isShowNavPos(){ + if(cr.isShowNavPos()!=null) + return cr.isShowNavPos(); + + else + return Globals.displayRuntimeOptionsAsDefault(); + + } + public void setShowNavPos(boolean value){ + cr.setShowNavPos(value); + } + + public boolean isShowGotoOption(){ + if(cr.isShowGotoOption()!=null) + return cr.isShowGotoOption(); + + else + return Globals.displayRuntimeOptionsAsDefault(); + + } + public void setShowGotoOption(boolean value){ + cr.setShowGotoOption(value); + } + + public boolean isPageNav(){ + + if(cr.isPageNav()!=null) + return cr.isPageNav(); + + else + return Globals.displayRuntimeOptionsAsDefault(); + + } + + public void setPageNav(boolean value){ + cr.setPageNav(value); + } + + + public String getNavPosition(){ + if(cr.getNavPosition()!=null) + return cr.getNavPosition(); + + else + return "top"; + //return cr.getNavPosition(); + } + public void setNavPosition(String value){ + cr.setNavPosition(value); + } + + + public String getDashboardEditor(){ + return getDashBoardReportsNew().getDashboardEditor(); + } + + public void setDashboardEditor(String value){ + getDashBoardReportsNew().setDashboardEditor(value); + } + + + public DashboardEditorList getDashboardEditorList(){ + return getDashBoardReportsNew().getDashboardEditorList(); + } + + public void setDashboardEditorList(DashboardEditorList value){ + getDashBoardReportsNew().setDashboardEditorList(value); + } + + public PDFAdditionalOptions getPDFAdditionalOptions() { + try { + if(cr.getPdfAdditionalOptions()==null) + addPDFAdditionalOptions(new ObjectFactory()); + } catch(RaptorException ex) { + ex.printStackTrace(); + } + return cr.getPdfAdditionalOptions(); + } + + public String getPDFFont(){ + return getPDFAdditionalOptions().getPDFFont()!=null?getPDFAdditionalOptions().getPDFFont():Globals.getDataFontFamily(); + } + public void setPDFFont(String value){ + getPDFAdditionalOptions().setPDFFont(value); + } + + public int getPDFFontSize() { + return getPDFAdditionalOptions().getPDFFontSize()==null?9:getPDFAdditionalOptions().getPDFFontSize(); + } + public void setPDFFontSize(int value){ + getPDFAdditionalOptions().setPDFFontSize(value); + } + + public String getPDFOrientation(){ + return getPDFAdditionalOptions().getPDFOrientation()!=null?"portrait":"landscape"; + } + public void setPDFOrientation(String value){ + getPDFAdditionalOptions().setPDFOrientation(value); + } + + public String getPDFLogo1(){ + return getPDFAdditionalOptions().getPDFLogo1(); + } + public void setPDFLogo1(String value){ + getPDFAdditionalOptions().setPDFLogo1(value); + } + + public String getPDFLogo2(){ + return getPDFAdditionalOptions().getPDFLogo2(); + } + public void setPDFLogo2(String value){ + getPDFAdditionalOptions().setPDFLogo2(value); + } + + public int getPDFLogo1Size() { + return getPDFAdditionalOptions().getPDFLogo1Size()==null?0:getPDFAdditionalOptions().getPDFLogo1Size(); + } + public void setPDFLogo1Size(int value){ + getPDFAdditionalOptions().setPDFLogo1Size(value); + } + + public int getPDFLogo2Size() { + return getPDFAdditionalOptions().getPDFLogo2Size()==null?0:getPDFAdditionalOptions().getPDFLogo2Size(); + } + public void setPDFLogo2Size(int value){ + getPDFAdditionalOptions().setPDFLogo2Size(value); + } + + public boolean isPDFCoverPage(){ + + if(getPDFAdditionalOptions().isPDFCoverPage()!=null) + return getPDFAdditionalOptions().isPDFCoverPage(); + + else + return true; + + } + + public void setPDFCoverPage(boolean value){ + getPDFAdditionalOptions().setPDFCoverPage(value); + } + + public String getPDFFooter1(){ + return getPDFAdditionalOptions().getPDFFooter1(); + } + public void setPDFFooter1(String value){ + getPDFAdditionalOptions().setPDFFooter1(value); + } + + public String getPDFFooter2(){ + return getPDFAdditionalOptions().getPDFFooter2(); + } + public void setPDFFooter2(String value){ + getPDFAdditionalOptions().setPDFFooter2(value); + } + + + +//End of Additional Methods + + public String getDataContainerHeight() { + return cr.getDataContainerHeight(); + } + + public String getDataContainerWidth() { + return cr.getDataContainerWidth(); + } + + public boolean isAllowSchedule() { + String allowSchedule = getAllowSchedule(); + return (allowSchedule !=null )? allowSchedule.startsWith("Y"):false; + } + + public String getAllowSchedule() { + return cr.getAllowSchedule(); + } + + /* Multi Group */ + + public boolean isMultiGroupColumn() { + String multiGroupColumn = getMultiGroupColumn(); + return (multiGroupColumn !=null )? multiGroupColumn.startsWith("Y"):false; + } + + public String getMultiGroupColumn() { + return cr.getMultiGroupColumn(); + } + + public void setMultiGroupColumn(String value) { + cr.setMultiGroupColumn(value); + } + + private int getColumnGroupLevel(String colId) throws RaptorException { + DataColumnType dc = getColumnById(colId); + return (dc == null) ? 0 : dc.getLevel(); + } // getColumnGroupLevel + + public int getMaxGroupLevel() { + List reportCols = getAllColumns(); + int maxLevel = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.getLevel()!=null) { + if(maxLevel < dc.getLevel()) + maxLevel = dc.getLevel(); + } + } // for + return maxLevel; + } // getMaxGroupLevel + + private int getColumnGroupStart(String colId) throws RaptorException { + DataColumnType dc = getColumnById(colId); + return (dc == null) ? 0 : dc.getStart(); + } // getColumnGroupStart + + private int getColumnGroupColSpan(String colId) throws RaptorException { + DataColumnType dc = getColumnById(colId); + return (dc == null) ? 0 : dc.getColspan(); + } // getColumnGroupColSpan + + public void setTopDown(String value) { + cr.setTopDown(value); + } + + public boolean isTopDown() { + String topDown = getTopDownOption(); + return (topDown !=null )? topDown.startsWith("Y"):false; + } + + public String getTopDownOption() { + return cr.getTopDown(); + } + + public void setSizedByContent(String value) { + cr.setSizedByContent(value); + } + + public boolean isSizedByContent() { + String sizedByContent = getSizedByContentOption(); + return (sizedByContent !=null )? sizedByContent.startsWith("Y"):false; + } + + public String getSizedByContentOption() { + return cr.getSizedByContent(); + } + + public String getDashboardOptions() { + return cr.getDashboardOptions(); + } + + public boolean isDashboardOptionHideChart() { + return nvl(getDashboardOptions()).length() > 0 && (getDashboardOptions().charAt(0) == 'Y'); + } + + public boolean isDashboardOptionHideData() { + return nvl(getDashboardOptions()).length() > 0 && (getDashboardOptions().charAt(1) == 'Y'); + } + + public boolean isDashboardOptionHideBtns() { + return nvl(getDashboardOptions()).length() > 0 && (getDashboardOptions().charAt(2) == 'Y'); + } + + public boolean isDisplayOptionHideForm() { + return nvl(getDisplayOptions()).length() > 0 && (getDisplayOptions().charAt(0) == 'Y'); + } + + public boolean isDisplayOptionHideChart() { + return nvl(getDisplayOptions()).length() > 1 && (getDisplayOptions().charAt(1) == 'Y'); + } + + public boolean isDisplayOptionHideData() { + return nvl(getDisplayOptions()).length() > 2 && (getDisplayOptions().charAt(2) == 'Y'); + } + + public boolean isDisplayOptionHideBtns() { + return nvl(getDisplayOptions()).length() > 3 && (getDisplayOptions().charAt(3) == 'Y'); + } + + public boolean isDisplayOptionHideMap() { + return nvl(getDisplayOptions()).length() > 4 && (getDisplayOptions().charAt(4) == 'Y'); + } + + public boolean isDisplayOptionHideExcelIcons() { + return nvl(getDisplayOptions()).length() > 5 && (getDisplayOptions().charAt(5) == 'Y'); + } + + public boolean isDisplayOptionHidePDFIcons() { + return nvl(getDisplayOptions()).length() > 6 && (getDisplayOptions().charAt(6) == 'Y'); + } + + public String getComment() { + return cr.getComment(); + } + + public DataSourceList getDataSourceList() { + return cr.getDataSourceList(); + } + + public ChartAdditionalOptions getChartAdditionalOptions() { + return cr.getChartAdditionalOptions(); + } + + public ChartDrillOptions getChartDrillOptions() { + return cr.getChartDrillOptions(); + } + + + public DataminingOptions getDataminingOptions() { + return cr.getDataminingOptions(); + } + + public DashboardReports getDashBoardReports() { + return cr.getDashBoardReports(); + } + + + public DashboardReportsNew getDashBoardReportsNew() { + try { + if(cr.getDashBoardReportsNew()==null) + addDashboardReportsNew(new ObjectFactory()); + } catch(RaptorException ex) { + ex.printStackTrace(); + } + return cr.getDashBoardReportsNew(); + } + + public String getDashboardLayoutHTML() { + return cr.getDashboardLayoutHTML(); + } + + public FormFieldList getFormFieldList() { + return cr.getFormFieldList(); + } + + public JavascriptList getJavascriptList() { + return cr.getJavascriptList(); + } + + public SemaphoreList getSemaphoreList() { + return cr.getSemaphoreList(); + } + + public void setPageSize(int value) { + cr.setPageSize(value); + } + + public void setAllowSchedule(String value) { + cr.setAllowSchedule(value); + } + + public void setMaxRowsInExcelDownload(int value) { + cr.setMaxRowsInExcelDownload(value); + } + + public void setReportInNewWindow (boolean value) { + cr.setReportInNewWindow(value); + } + + public void setDisplayFolderTree (boolean value) { + cr.setDisplayFolderTree(value); + } + + public void setReportType(String value) { + cr.setReportType(value); + } + + public void setReportName(String value) { + cr.setReportName(value); + } + + public void setDBInfo(String value) { + if (!(cr.getDbInfo() != null && cr.getDbInfo().length() > 0)) + cr.setDbInfo(value); + } + + public void setDBType(String value) { + if (!(cr.getDbType() != null && cr.getDbType().length() > 0)) + cr.setDbType(value); + } + + public void setReportDescr(String value) { + cr.setReportDescr(value); + } + + public void setChartType(String value) { + cr.setChartType(value); + } + + public void setChartMultiplePieOrder(String value) { + cr.getChartAdditionalOptions().setChartMultiplePieOrder(value); + } + + public void setChartMultiplePieLabelDisplay(String value) { + cr.getChartAdditionalOptions().setChartMultiplePieLabelDisplay(value); + } + + public void setChartOrientation(String value) { + cr.getChartAdditionalOptions().setChartOrientation(value); + } + + public void setSecondaryChartRenderer(String value) { + cr.getChartAdditionalOptions().setSecondaryChartRenderer(value); + } + + public void setOverlayItemValueOnStackBar(String value) { + cr.getChartAdditionalOptions().setOverlayItemValueOnStackBar(value); + } + + public void setIntervalFromdate(String value) { + cr.getChartAdditionalOptions().setIntervalFromdate(value); + } + + public void setIntervalLabel(String value) { + cr.getChartAdditionalOptions().setIntervalLabel(value); + } + + public void setIntervalTodate(String value) { + cr.getChartAdditionalOptions().setIntervalTodate(value); + } + + public void setLegendPosition(String value) { + cr.getChartAdditionalOptions().setLegendPosition(value); + } + + public void setLegendLabelAngle(String value) { + cr.getChartAdditionalOptions().setLabelAngle(value); + } + + public void setMaxLabelsInDomainAxis(String value) { + if(nvl(value).length()<=0) value = "99"; + cr.getChartAdditionalOptions().setMaxLabelsInDomainAxis(value); + } + + public void setLastSeriesALineChart(String value) { + cr.getChartAdditionalOptions().setLastSeriesALineChart(value); + } + + public void setLastSeriesABarChart(String value) { + cr.getChartAdditionalOptions().setLastSeriesABarChart(value); + } + + public void setChartDisplay(String value) { + cr.getChartAdditionalOptions().setChartDisplay(value); + } + + public void setChartAnimate(boolean animate) { + if(cr.getChartAdditionalOptions()!=null) + cr.getChartAdditionalOptions().setAnimate(animate); + else { + try { + if(getChartAdditionalOptions()==null) + addChartAdditionalOptions(new ObjectFactory()); + } catch(RaptorException ex) { + ex.printStackTrace(); + } + if(cr.getChartAdditionalOptions()!=null) + cr.getChartAdditionalOptions().setAnimate(animate); + + } + + } + + public void addChartAdditionalOptions(ObjectFactory objFactory) throws RaptorException { + ChartAdditionalOptions chartOptions = objFactory.createChartAdditionalOptions(); + cr.setChartAdditionalOptions(chartOptions); + } + + public void addDashboardReportsNew(ObjectFactory objFactory) throws RaptorException { + DashboardReportsNew dashboardReports = objFactory.createDashboardReportsNew(); + cr.setDashBoardReportsNew(dashboardReports); + } + + public void addPDFAdditionalOptions(ObjectFactory objFactory) throws RaptorException { + PDFAdditionalOptions pdfOptions = objFactory.createPDFAdditionalOptions(); + cr.setPdfAdditionalOptions(pdfOptions); + } + + public void setChartTypeFixed(String value) { + cr.setChartTypeFixed(value); + } + + public void setChartLeftAxisLabel(String value) { + cr.setChartLeftAxisLabel(value); + } + + public void setChartRightAxisLabel(String value) { + cr.setChartRightAxisLabel(value); + } + + public void setChartWidth(String value) { + cr.setChartWidth(value); + } + + public void setChartHeight(String value) { + cr.setChartHeight(value); + } + + public void setChartMultiSeries(String value) { + cr.setChartMultiSeries(value); + } + + public void setPublic(boolean value) { + cr.setPublic(value); + if (reportSecurity != null) + reportSecurity.setPublic(value); + } + + // public void setCreateId(String value) { cr.setCreateId(value); } + // public void setCreateDate(Calendar value) { cr.setCreateDate(value); } + public void setReportSQL(String value) { + cr.setReportSQL(value); + } + + public void setReportTitle(String value) { + cr.setReportTitle(value); + } + + public void setReportSubTitle(String value) { + cr.setReportSubTitle(value); + } + + public void setReportHeader(String value) { + cr.setReportHeader(value); + } + + public void setReportFooter(String value) { + cr.setReportFooter(value); + } + + public void setNumFormCols(String value) { + cr.setNumFormCols(value); + } + + public void setNumDashCols(String value) { + cr.setNumDashCols(value); + } + + public void setDisplayOptions(String value) { + cr.setDisplayOptions(value); + } + + public void setDataContainerHeight(String value) { + cr.setDataContainerHeight(value); + } + + public void setDataContainerWidth(String value) { + cr.setDataContainerWidth(value); + } + + public void setDashboardOptions(String value) { + cr.setDashboardOptions(value); + } + + public void setComment(String value) { + cr.setComment(value); + } + + public void setDashboardType(boolean dashboardType) { + cr.setDashboardType(dashboardType); + } + + public void setDashboardLayoutHTML(String html) { + cr.setDashboardLayoutHTML(html); + } + + public void setDataSourceList(DataSourceList value) { + cr.setDataSourceList(value); + } + + public void setFormFieldList(FormFieldList value) { + cr.setFormFieldList(value); + } + + public void setDashBoardReports(DashboardReports value) { + cr.setDashBoardReports(value); + } + + public void setSemaphoreList(SemaphoreList value) { + cr.setSemaphoreList(value); + } + + public void setJavascriptList(JavascriptList value) { + cr.setJavascriptList(value); + } + + public void setJavascriptElement(String javascriptElement) { + cr.setJavascriptElement(javascriptElement); + } + + public void checkUserReadAccess(HttpServletRequest request) throws RaptorException { + reportSecurity.checkUserReadAccess(request, null); + } + public void checkUserReadAccess(HttpServletRequest request, String userID) throws RaptorException { + reportSecurity.checkUserReadAccess(request, userID); + } + + public void checkUserWriteAccess(HttpServletRequest request) throws RaptorException { + reportSecurity.checkUserWriteAccess(request); + verifySQLBasedReportAccess(request); + } + + public String getOwnerID() { + return reportSecurity.getOwnerID(); + } + + public String getCreateID() { + return reportSecurity.getCreateID(); + } + + public String getCreateDate() { + return reportSecurity.getCreateDate(); + } + + public String getUpdateID() { + return reportSecurity.getUpdateID(); + } + + public String getUpdateDate() { + return reportSecurity.getUpdateDate(); + } + + public ReportSecurity getReportSecurity() { + return reportSecurity; + } + + /****Report Maps - Start****/ + public ReportMap getReportMap() { + return cr.getReportMap(); + } + + public void setReportMap(ReportMap reportMap) { + cr.setReportMap(reportMap); + } + /****Report Maps - End****/ + + /****Report Chart Drilldown - Start****/ + public ChartDrillOptions getReportChartDrillOptions() { + return cr.getChartDrillOptions(); + } + + public void setReportChartDrillOptions(ChartDrillOptions chartDrillOptions) { + cr.setChartDrillOptions(chartDrillOptions); + } + /****Report Maps - End****/ + + + /** ************************************************************************************************* */ + + public String getFormHelpText() { + String formHelpText = nvl(getComment()); + + if (formHelpText.indexOf('|') >= 0) + formHelpText = formHelpText.substring(formHelpText.lastIndexOf('|') + 1); + + return formHelpText; + } // getFormHelpText + + public void setFormHelpText(String formHelpText) { + String comment = nvl(getComment()); + + if (comment.indexOf('|') >= 0) + comment = comment.substring(0, comment.lastIndexOf('|')); + if (comment.length() > 0) + comment += '|'; + + setComment(comment + formHelpText); + } // setFormHelpText + + public boolean isRuntimeColSortDisabled() { + String comment = nvl(getComment()); + + if (comment.indexOf('|') < 0) + return false; + + return comment.substring(0, comment.indexOf('|')).equals("Y"); + } // isRuntimeColSortDisabled + + public void setRuntimeColSortDisabled(boolean value) { + String comment = nvl(getComment()); + + if (comment.indexOf('|') >= 0) + comment = comment.substring(comment.indexOf('|') + 1); + + setComment((value ? "Y" : "N") + "|" + comment); + } // setRuntimeColSortDisabled + + /** ************************************************************************************************* */ + + protected void verifySQLBasedReportAccess(HttpServletRequest request) throws RaptorException { + String userID = AppUtils.getUserID(request); + if (getReportDefType().equals(AppConstants.RD_SQL_BASED) + && (!Globals.getAllowSQLBasedReports()) && (!AppUtils.isAdminUser(request))) + throw new org.openecomp.portalsdk.analytics.error.UserAccessException(reportID, "[" + userID + "] " + + AppUtils.getUserName(request), AppConstants.UA_WRITE); + } // verifySQLBasedReportAccess + + /** ************************************************************************************************* */ + + private String getColumnNameById(String colId) throws RaptorException { + DataColumnType dc = getColumnById(colId); + return (dc == null) ? "NULL" : dc.getColName(); + } // getColumnNameById + + // Checks if drill-down URL points to individual record display (return + // true) or another report (return false) + private boolean isViewAction(String value) throws RaptorException { + try { + Vector viewActions = org.openecomp.portalsdk.analytics.model.DataCache.getDataViewActions(); + + for (int i = 0; i < viewActions.size(); i++) + if (value.equals(AppUtils.getBaseActionURL() + ((String) viewActions.get(i)))) + return true; + } catch (Exception e) { + throw new RaptorRuntimeException("ReportWrapper.isViewAction Exception: " + + e.getMessage()); + } + + return false; + } // isViewAction + + public String getSelectExpr(DataColumnType dct) { + // String colName = + // dct.isCalculated()?dct.getColName():((nvl(dct.getTableId()).length()>0)?(dct.getTableId()+"."+dct.getColName()):dct.getColName()); + return getSelectExpr(dct, dct.getColName() /* colName */); + } // getSelectExpr + + /*private String getSelectExpr(DataColumnType dct, String colName) { + String colType = dct.getColType(); + if (colType.equals(AppConstants.CT_CHAR) + || ((nvl(dct.getColFormat()).length() == 0) && (!colType + .equals(AppConstants.CT_DATE)))) + return colName; + else + return "TO_CHAR(" + colName + ", '" + + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')"; + } // getSelectExpr + */ + + private String getSelectExpr(DataColumnType dct, String colName) { + String colType = dct.getColType(); + if(colType.equals(AppConstants.CT_NUMBER)) { + return colName; + } else + if (colType.equals(AppConstants.CT_CHAR) + || ((nvl(dct.getColFormat()).length() == 0) && (!colType + .equals(AppConstants.CT_DATE)))) + return colName; + + else + return "TO_CHAR(" + colName + ", '" + + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')"; + } // getSelectExpr + + + /** ************************************************************************************************* */ + + public DataSourceType getTableById(String tableId) { + for (Iterator iter = getDataSourceList().getDataSource().iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + if (ds.getTableId().equals(tableId)) + return ds; + } // for + + return null; + } // getTableById + + public DataSourceType getTableByDBName(String tableName) { + for (Iterator iter = getDataSourceList().getDataSource().iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + if (ds.getTableName().equals(tableName)) + return ds; + } // for + + return null; + } // getTableByDBName + + public DataSourceType getColumnTableById(String colId) { + return getTableById(getColumnById(colId).getTableId()); + } // getColumnTableById + + public DataColumnType getColumnById(String colId) { + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.getColId().toLowerCase().equals(colId.toLowerCase())) + return dc; + } // for + + return null; + } // getColumnById + + public DataColumnType getChartLegendColumn() { + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + return dc; + } // for + return null; + } // getChartLegendColumn + + /* + * public DataColumnType getChartValueColumn() { List reportCols = + * getAllColumns(); for(Iterator iter=reportCols.iterator(); iter.hasNext(); ) { + * DataColumnType dc = (DataColumnType) iter.next(); if(dc.getChartSeq()>0) + * return dc; } // for + * + * return null; } // getChartValueColumn + */ + + public List getChartValueColumnsList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = getAllColumns(); + + ArrayList chartValueCols = new ArrayList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 ) { + if(!AppUtils.nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } + else if(filter == 0) chartValueCols.add(dc); + } else chartValueCols.add(dc); + } + } +// } else +// chartValueCols.add(dc); + } // for + Collections.sort(chartValueCols, new ChartSeqComparator()); + return chartValueCols; + } // getChartValueColumnsList + + + /* public ListModelList getChartValueColumnsListModelList( int filter, HashMap formValues) { / *filter; all=0;create without new chart =1; createNewChart=2 * / + List reportCols = getAllColumns(); + + ArrayList chartValueCols = new ArrayList(); + ListModelList chartValueListModelList = new ListModelList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 ) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } + else if(filter == 0) chartValueCols.add(dc); + } else chartValueCols.add(dc); + } +// } else +// chartValueCols.add(dc); + chartValueListModelList.add(new Item(dc.getColId(), dc.getDisplayName())); + } // for + Collections.sort(chartValueCols, new ChartSeqComparator()); + return chartValueListModelList; + } // getChartValueColumnsList */ + + + /** Check whether chart has series (Category) columns **/ + public boolean hasSeriesColumn() { + List reportCols = getAllColumns(); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.isChartSeries()!=null && dc.isChartSeries().booleanValue()) + return true; + } // for + return false; + } // hasSeriesColumn + + + public List getChartDisplayNamesList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = getAllColumns(); + ArrayList chartValueColNames = new ArrayList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue()) ) { + chartValueColNames.add(dc.getDisplayName()); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueColNames.add(dc.getDisplayName()); + } + else if(filter == 0) chartValueColNames.add(dc.getDisplayName()); + } else if(filter == 0) chartValueColNames.add(dc.getDisplayName()); + } + // } else + // chartValueColNames.add(dc.getDisplayName()); + + } + return chartValueColNames; + } // getChartDisplayNamesList + + + public List getChartColumnColorsList(int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = getAllColumns(); + ArrayList chartValueColColors = new ArrayList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue()) ) { + chartValueColColors.add(dc.getChartColor()); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueColColors.add(dc.getChartColor()); + } + else if(filter == 0) chartValueColColors.add(dc.getChartColor()); + } else if(filter == 0) chartValueColColors.add(dc.getChartColor()); + } +// } else +// chartValueColColors.add(dc.getChartColor()); + } + return chartValueColColors; + } // getChartColumnColorsList + + public List getChartValueColumnAxisList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = getAllColumns(); + ArrayList chartValueColAxis = new ArrayList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) { + chartValueColAxis.add(nvl(dc.getColOnChart(), "0")); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueColAxis.add(nvl(dc.getColOnChart(), "0")); + } + else if(filter == 0) chartValueColAxis.add(nvl(dc.getColOnChart(), "0")); + } else if(filter == 0) chartValueColAxis.add(nvl(dc.getColOnChart(), "0")); + } +// } else +// chartValueColAxis.add(nvl(dc.getColOnChart(), "0")); + } + return chartValueColAxis; + } // getChartColumnAxisList + + + public List getChartValueNewChartList() { + ArrayList chartValueNewChartAxis = new ArrayList(); + for (Iterator iter = getChartValueColumnsList(2, null).iterator(); iter.hasNext();) + chartValueNewChartAxis.add(new Boolean(((DataColumnType) iter.next()).isCreateInNewChart())); + return chartValueNewChartAxis; + } // getChartValueNewChartList + + public List getAllChartGroups() { + ArrayList chartGroups = new ArrayList(); + String chartGroupName=""; + List reportCols = getAllColumns(); + Set groupSet = new TreeSet(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(dc.getChartSeq()!=null && dc.getChartSeq()> 0) { + chartGroupName = dc.getChartGroup(); + if(nvl(chartGroupName).length()>0) + groupSet.add(chartGroupName); + } + } + List l = new ArrayList(groupSet); + return l; + } // getAllChartGroups + + public HashMap getAllChartYAxis(ReportParamValues reportParamValues) { + String chartYAxis=""; + List reportCols = getAllColumns(); + HashMap hashMap = new HashMap(); + FormFieldList formFieldList = getFormFieldList(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(dc.getChartSeq()!=null && dc.getChartSeq()> 0) { + chartYAxis = dc.getYAxis(); + if(formFieldList!=null && reportParamValues!=null) { + for (Iterator iter1 = getFormFieldList().getFormField().iterator(); iter1.hasNext();) { + FormFieldType fft = (FormFieldType) iter1.next(); + String fieldDisplay = getFormFieldDisplayName(fft); + String fieldId = fft.getFieldId(); + if(!fft.getFieldType().equals(FormField.FFT_BLANK) && !fft.getFieldType().equals(FormField.FFT_LIST_MULTI) && !fft.getFieldType().equals(FormField.FFT_TEXTAREA)) { + String paramValue = Utils.oracleSafe(nvl(reportParamValues.getParamValue(fieldId))); + chartYAxis = Utils.replaceInString(chartYAxis, fieldDisplay, nvl( + paramValue, "")); + } + } + } + if(nvl(dc.getChartGroup()).length()>0) + hashMap.put(dc.getChartGroup(),chartYAxis); + } + } + return hashMap; + } // getAllChartGroups + + public List getChartGroupColumnAxisList( String chartGroupName, HashMap formValues ) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = getAllColumns(); + ArrayList chartGroupColAxis = new ArrayList(); + String chartGroup = chartGroupName.substring(0,chartGroupName.lastIndexOf("|")); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0) { + if( nvl(dc.getChartGroup()).indexOf("|") > 0 && (nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup))) { + //if( nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup)) { + //System.out.println("$$$$$$$DC " + dc.getColId()+ " " + dc.getColOnChart()); + chartGroupColAxis.add(dc); + } + } +// } else +// chartValueColAxis.add(nvl(dc.getColOnChart(), "0")); + } + Collections.sort(chartGroupColAxis, new ChartSeqComparator()); + return chartGroupColAxis; + } // getChartColumnAxisList + + public List getChartGroupValueColumnAxisList( String chartGroupName, HashMap formValues ) { + List reportCols = getAllColumns(); + String index = chartGroupName.substring(chartGroupName.lastIndexOf("|")+1); + String chartGroup = chartGroupName.substring(0,chartGroupName.lastIndexOf("|")); + //System.out.println("$$$$INDEX " + index); + ArrayList chartGroupValueColAxis = new ArrayList(); + int flag = 0; + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0) { + //System.out.println(" Chartgroup " + dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))); + if( nvl(dc.getChartGroup()).indexOf("|") > 0 && (nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup))) { + //if( nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup)) { + //System.out.println(" Added Chartgroupname " + chartGroup + " " + dc.getChartGroup() + " " + index); + chartGroupValueColAxis.add(dc); + } + } + } + return chartGroupValueColAxis; + } // getChartColumnAxisList + + public List getChartGroupDisplayNamesList( String chartGroupName, HashMap formValues) { + List reportCols = getAllColumns(); + ArrayList chartGroupValueColNames = new ArrayList(); + String chartGroup = chartGroupName.substring(0,chartGroupName.lastIndexOf("|")); + int flag = 0; + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); + //System.out.println("$$$$$CHART " + dc.getChartSeq()+ " " + dc.getChartGroup()+ " " + chartGroup); + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 ) { + if( nvl(dc.getChartGroup()).indexOf("|") > 0 && (nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup))) { + chartGroupValueColNames.add(dc.getDisplayName()); + } + } + } + return chartGroupValueColNames; + } // getChartDisplayNamesList + + + public List getChartGroupColumnColorsList(String chartGroupName, HashMap formValues) { + List reportCols = getAllColumns(); + ArrayList chartValueColColors = new ArrayList(); + String chartGroup = chartGroupName.substring(0,chartGroupName.lastIndexOf("|")); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); + flag = getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 ) { + if( nvl(dc.getChartGroup()).indexOf("|") > 0 && (nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup))) { + //if( nvl(dc.getChartGroup().substring(0,dc.getChartGroup().lastIndexOf("|"))).equals(chartGroup)) { + chartValueColColors.add(dc.getChartColor()); + } + } + } + return chartValueColColors; + } // getChartColumnColorsList + + + public List getCrossTabRowColumns() { + List reportCols = getAllColumns(); + Vector v = new Vector(reportCols.size()); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_ROW)) + v.add(dc); + } // for + + return v; + } // getCrossTabRowColumns + + public List getCrossTabColColumns() { + List reportCols = getAllColumns(); + Vector v = new Vector(reportCols.size()); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) + v.add(dc); + } // for + + return v; + } // getCrossTabColColumns + + public String getCrossTabDisplayTotal(String rowColPos) { + DataColumnType dct = getCrossTabValueColumn(); + if (dct == null) + return ""; + + String displayTotal = nvl(dct.getDisplayTotal()); + if (displayTotal.indexOf('|') >= 0) { + String displayColTotal = displayTotal.substring(0, displayTotal.indexOf('|')); + String displayRowTotal = displayTotal.substring(displayTotal.indexOf('|') + 1); + + if (rowColPos.equals(AppConstants.CV_COLUMN)) + displayTotal = displayColTotal; + else if (rowColPos.equals(AppConstants.CV_ROW)) + displayTotal = displayRowTotal; + else if (displayColTotal.equals(displayRowTotal)) + displayTotal = displayColTotal; + } // if + + return displayTotal; + } // getCrossTabDisplayTotal + + public DataColumnType getCrossTabValueColumn() { + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_VALUE)) + return dc; + } // for + + return null; + } // getCrossTabValueColumn + + public int getCrossTabValueColumnIndex() { // Returns the index counting + // only visible columns + List reportCols = getAllColumns(); + + int idx = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_VALUE)) + break; + if (dc.isVisible()) + idx++; + } // for + + return idx; + } // getCrossTabValueColumnIndex + + public ColFilterType getFilterById(String colId, int filterIndex) { + DataColumnType dc = getColumnById(colId); + try { + return (ColFilterType) dc.getColFilterList().getColFilter().get(filterIndex); + } catch (Exception e) { + return null; + } + } // getFilterById + + public boolean needFormInput() { + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (dct.getColFilterList() != null) { + List fList = dct.getColFilterList().getColFilter(); + for (Iterator iterF = fList.iterator(); iterF.hasNext();) { + ColFilterType cft = (ColFilterType) iterF.next(); + + if (nvl(cft.getArgType()).equals(AppConstants.AT_FORM)) + return true; + } // for + } // if + } // for + + return false; + } // needFormInput + + public int getNumSortColumns() { + int numSortCols = 0; + for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + if (dct.getOrderBySeq() != null && dct.getOrderBySeq() > 0) + numSortCols++; + } // for + + return numSortCols; + } // getNumSortColumns + + public SemaphoreType getSemaphoreById(String semaphoreId) { + if (getSemaphoreList() != null && semaphoreId != null) + for (Iterator iter = getSemaphoreList().getSemaphore().iterator(); iter.hasNext();) { + SemaphoreType sem = (SemaphoreType) iter.next(); + if (sem.getSemaphoreId().equals(semaphoreId)) + return sem; + } // for + + return null; + } // getSemaphoreById + + public void deleteSemaphore(SemaphoreType semaphore) { + if (getSemaphoreList() != null) { + if(getSemaphoreList().getSemaphore()!= null) + getSemaphoreList().getSemaphore().remove((SemaphoreType) semaphore); + } + } // deleteSemaphore + + + public void setSemaphore(SemaphoreType sem) { + if (getSemaphoreList() != null) { + getSemaphoreList().getSemaphore().add(sem); + } + + } // setSemaphore + + public static FormatType getSemaphoreFormatById(SemaphoreType semaphore, String formatId) { + if (semaphore != null) + for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter + .hasNext();) { + FormatType fmt = (FormatType) iter.next(); + if (fmt.getFormatId().equals(formatId)) + return fmt; + } // for + + return null; + } // getSemaphoreFormatById + + public FormFieldType getFormFieldById(String fieldId) { + if (getFormFieldList() != null && fieldId != null) + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + if (fft.getFieldId().equals(fieldId)) + return fft; + } // for + + return null; + } // getFormFieldById + + public FormFieldType getFormFieldByDisplayValue(String fieldDisplay) { + // fieldDisplay expected to be [fieldName] + if (getFormFieldList() != null && fieldDisplay != null) + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + if (fieldDisplay.equals(getFormFieldDisplayName(fft))) + return fft; + } // for + + return null; + } // getFormFieldById + + public String getFormFieldDisplayName(FormFieldType fft) { + return "[" + fft.getFieldName() + "]"; + } // getFormFieldDisplayName + + /** ************************************************************************************************* */ + + public void resetCache(boolean sqlOnly) { + generatedSQL = null; + if (!sqlOnly) { + allColumns = null; + allFilters = null; + } + } // resetCache + + public String getOuterJoinType(DataSourceType curTable) { + String refDefinition = nvl(curTable.getRefDefinition()); + int outerJoinIdx = refDefinition.indexOf(" (+)"); + if (outerJoinIdx < 0) + // No outer join + return ""; + + int equalSignIdx = refDefinition.indexOf("="); + if (refDefinition.indexOf(curTable.getTableId()) < equalSignIdx) + // Cur. table is on the left side + return (outerJoinIdx < equalSignIdx) ? AppConstants.OJ_CURRENT + : AppConstants.OJ_JOINED; + else + // Joined table is on the left side + return (outerJoinIdx < equalSignIdx) ? AppConstants.OJ_JOINED + : AppConstants.OJ_CURRENT; + } // getOuterJoinType + + public String getFormFieldName(ColFilterType filter) { + FormFieldType fft = null; + if (filter.getArgType().equals(AppConstants.AT_FORM)) + fft = getFormFieldByDisplayValue(filter.getArgValue()); + + return (fft != null) ? fft.getFieldId() : filter.getColId() + "_f" + + filter.getFilterSeq(); + } // getFormFieldName + + public String getFormFieldDisplayName(DataColumnType column, ColFilterType filter) { + FormFieldType fft = null; + if (filter.getArgType().equals(AppConstants.AT_FORM)) + fft = getFormFieldByDisplayValue(filter.getArgValue()); + + return (fft != null) ? fft.getFieldName() : column.getDisplayName() + " " + + filter.getExpression(); + } // getFormFieldDisplayName + + public Calendar getFormFieldRangeStart(ColFilterType filter) { + FormFieldType fft = null; + if (filter.getArgType().equals(AppConstants.AT_FORM)) + fft = getFormFieldByDisplayValue(filter.getArgValue()); + + return (fft != null) ? fft.getRangeStartDate().toGregorianCalendar() : null; + } // getFormFieldRangeStart + + public Calendar getFormFieldRangeEnd(ColFilterType filter) { + FormFieldType fft = null; + if (filter.getArgType().equals(AppConstants.AT_FORM)) + fft = getFormFieldByDisplayValue(filter.getArgValue()); + + //System.out.println("as " + fft.getRangeEndDate()); + return (fft != null) ? fft.getRangeEndDate().toGregorianCalendar() : null; + } // getFormFieldRangeEnd + + public String getFormFieldRangeStartSQL(ColFilterType filter) { + FormFieldType fft = null; + if (filter.getArgType().equals(AppConstants.AT_FORM)) + fft = getFormFieldByDisplayValue(filter.getArgValue()); + + return (fft != null) ? fft.getRangeStartDateSQL() : null; + } // getFormFieldRangeStart + + public String getFormFieldRangeEndSQL(ColFilterType filter) { + FormFieldType fft = null; + if (filter.getArgType().equals(AppConstants.AT_FORM)) + fft = getFormFieldByDisplayValue(filter.getArgValue()); + + //System.out.println("as " + fft.getRangeEndDate()); + return (fft != null) ? fft.getRangeEndDateSQL() : null; + } // getFormFieldRangeEnd + + public String getUniqueTableId(String tableName) { + String tableIdPrefix = tableName.startsWith("MSA_") ? tableName.substring(4, 6) + : tableName.substring(0, 2); + String tableId = ""; + + int tableIdN = getDataSourceList().getDataSource().size() + 1; + do { + tableId = tableIdPrefix.toLowerCase() + (tableIdN++); + } while (getTableById(tableId) != null); + + return tableId; + } // getUniqueTableId + + /** ************************************************************************************************* */ + + protected void deleteDataSourceType(String tableId) { + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType dst = (DataSourceType) iter.next(); + if (dst.getTableId().equals(tableId)) + iter.remove(); + else if (nvl(dst.getRefTableId()).equals(tableId)) { + dst.setRefTableId(null); + dst.setRefDefinition(null); + } + } // for + + resetCache(false); + } // deleteDataSourceType + + public static void adjustColumnType(DataColumnType dct) { + dct.setColType(dct.getDbColType()); + + if (dct.isCalculated()) + if (dct.getColName().startsWith("SUM(") || dct.getColName().startsWith("COUNT(") + || dct.getColName().startsWith("AVG(") + || dct.getColName().startsWith("STDDEV(") + || dct.getColName().startsWith("VARIANCE(")) + dct.setColType(AppConstants.CT_NUMBER); + else if (dct.getColName().startsWith("DECODE(") || dct.getColName().startsWith("coalesce(")) + dct.setColType(AppConstants.CT_CHAR); + } // adjustColumnType + + public static boolean getColumnNoParseDateFlag(DataColumnType dct) { + return (nvls(dct.getComment()).indexOf(AppConstants.CF_NO_PARSE_DATE) >= 0); + } // getColumnNoParseDateFlag + + public static void setColumnNoParseDateFlag(DataColumnType dct, boolean noParseDateFlag) { + dct.setComment(noParseDateFlag ? AppConstants.CF_NO_PARSE_DATE : null); + } // setColumnNoParseDateFlag + + /** ************************************************************************************************* */ + + public static String getSQLBasedFFTColTableName(String fftColId) { + return fftColId.substring(0, fftColId.indexOf('.')); + } // getSQLBasedFFTColTableName + + public static String getSQLBasedFFTColColumnName(String fftColId) { + fftColId = (fftColId.indexOf('|') < 0) ? fftColId : fftColId.substring(0, fftColId + .indexOf('|')); + return fftColId.substring(fftColId.indexOf('.') + 1); + } // getSQLBasedFFTColColumnName + + public static String getSQLBasedFFTColDisplayFormat(String fftColId) { + return (fftColId.indexOf('|') < 0) ? "" : fftColId + .substring(fftColId.indexOf('|') + 1); + } // getSQLBasedFFTColDisplayFormat + + /** ************************************************************************************************* */ + + public List getAllColumns() { + if (cr == null) + throw new NullPointerException("CustomReport not initialized"); + + if (allColumns == null) { + allColumns = new Vector(); + + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + + // allColumns.addAll(ds.getDataColumnList().getDataColumn()); + List dcList = ds.getDataColumnList().getDataColumn(); + for (Iterator iterC = dcList.iterator(); iterC.hasNext();) { + DataColumnType dc = (DataColumnType) iterC.next(); + + allColumns.add(dc); + } // for + } // for + + Collections.sort(allColumns, new OrderSeqComparator()); + } // if + + return allColumns; + } // getAllColumns + + public List getOnlyVisibleColumns() { + if (cr == null) + throw new NullPointerException("CustomReport not initialized"); + + if (allVisibleColumns == null) { + allVisibleColumns = new Vector(); + + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + + // allColumns.addAll(ds.getDataColumnList().getDataColumn()); + List dcList = ds.getDataColumnList().getDataColumn(); + for (Iterator iterC = dcList.iterator(); iterC.hasNext();) { + DataColumnType dc = (DataColumnType) iterC.next(); + if(dc.isVisible()) + allVisibleColumns.add(dc); + } // for + } // for + + Collections.sort(allVisibleColumns, new OrderSeqComparator()); + } // if + + return allVisibleColumns; + } // getOnlyVisibleColumns + public int getVisibleColumnCount() { + if (cr == null) + throw new NullPointerException("CustomReport not initialized"); + int colCount = 0; + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + + // allColumns.addAll(ds.getDataColumnList().getDataColumn()); + List dcList = ds.getDataColumnList().getDataColumn(); + for (Iterator iterC = dcList.iterator(); iterC.hasNext();) { + DataColumnType dc = (DataColumnType) iterC.next(); + if(dc.isVisible()) colCount ++; + } // for + } // for + + return colCount; + } + + public List getAllFilters() { + if (cr == null) + throw new NullPointerException("CustomReport not initialized"); + + // if(allFilters==null) { + allFilters = new Vector(); + + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (dct.getColFilterList() != null) { + List colFilters = dct.getColFilterList().getColFilter(); + + for (Iterator iterF = colFilters.iterator(); iterF.hasNext();) { + ColFilterType cft = (ColFilterType) iterF.next(); + + allFilters.add(cft); + } // for + } // if + } // for + + // Collections.sort(allFilters, ??); + // } // if + + return allFilters; + } // getAllFilters + + private String formatValue(String value, DataColumnType dc, boolean useDefaultDateFormat) throws RaptorException { + return formatValue(value, dc, useDefaultDateFormat, getColumnTableById(dc.getColId()), null); + } // formatValue + + private String formatValue(String value, DataColumnType dc, boolean useDefaultDateFormat, + DataSourceType ds, FormFieldType fft) throws RaptorException { + String fmtValue = null; + + if (nvl(value).length() == 0) + fmtValue = ""; + else if (value.equals(AppConstants.FILTER_MAX_VALUE) + || value.equals(AppConstants.FILTER_MIN_VALUE)) + fmtValue = "(SELECT " + + (value.equals(AppConstants.FILTER_MAX_VALUE) ? "MAX" : "MIN") + "(" + + dc.getColName() + ") FROM " + ds.getTableName() + ")"; + else if (dc.getColType().equals(AppConstants.CT_NUMBER)) { + try { + double vD = Double.parseDouble(value); + fmtValue = value; + } catch(NumberFormatException ex) { + throw new UserDefinedException("Expected number, Given String for the form field \"" + fft.getFieldName()+"\""); + } + } + else if (dc.getColType().equals(AppConstants.CT_DATE)) { + if (fft!=null && (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) ) { + fmtValue = "TO_DATE('" + + value + + "', '" + + (useDefaultDateFormat ? AppConstants.DEFAULT_DATE_FORMAT : nvl(dc + .getColFormat(), AppConstants.DEFAULT_DATE_FORMAT));//+" HH24:MI:SS')"; + fmtValue = fmtValue + " HH24"; + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) + fmtValue = fmtValue + ":MI"; + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) + fmtValue = fmtValue + " HH24:MI:SS"; + } else { + fmtValue = "TO_DATE('" + + value + + "', '" + + (useDefaultDateFormat ? AppConstants.DEFAULT_DATE_FORMAT : nvl(dc + .getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)) + "')"; + if (Globals.getMonthFormatUseLastDay()) + if (!useDefaultDateFormat) + if (nvl(dc.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT).equals( + "MM/YYYY") + || nvl(dc.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + .equals("MONTH, YYYY")) + fmtValue = "ADD_MONTHS(" + fmtValue + ", 1)-1"; + } + }else { + fmtValue = value; + if (!fmtValue.startsWith("'")) + fmtValue = "'" + fmtValue + "'"; + } + + return fmtValue; + } // formatValue + + private String formatListValue(String listValue, DataColumnType dc, + boolean useDefaultDateFormat, boolean useOnlyPipeDelimiter) throws RaptorException { + return formatListValue("", listValue, dc, useDefaultDateFormat, useOnlyPipeDelimiter, + getColumnTableById(dc.getColId()), null); + } // formatListValue + + public String formatListValue(String fieldDisplay, String listValue, DataColumnType dc, + boolean useDefaultDateFormat, boolean useOnlyPipeDelimiter, DataSourceType ds, + String listBaseSQL) throws RaptorException { + StringBuffer fmtValue = new StringBuffer(""); + //if(nvl(listValue,"").trim().length()>0) { + // The below statement is commented so that pipe is taken out from parsing for text area form field +// StringTokenizer st = new StringTokenizer(listValue, useOnlyPipeDelimiter ? "|" + //: ",|\n\r\f"); + StringTokenizer st = new StringTokenizer(listValue, useOnlyPipeDelimiter ? "|" + : ",\n\r\f"); + + while (st.hasMoreTokens()) { + if (fmtValue.length() > 0) + fmtValue.append(", "); + + if (dc == null) { + // For SQL-based reports - value always string + String value = st.nextToken().trim(); + if (value.startsWith("'")) + fmtValue.append(value); + else + fmtValue.append("'" + value + "'"); + } else + fmtValue.append(formatValue(st.nextToken().trim(), dc, useDefaultDateFormat, + ds, null) ); + + } // while + + if (fmtValue.length() == 0) { + if(nvl(fieldDisplay).length() > 0) { + fmtValue.append(""); + } else { + fmtValue.append("("); + fmtValue.append(nvl(listBaseSQL, "NULL")); + fmtValue.append(")"); + } + } else if (fmtValue.charAt(0) != '(') { + fmtValue.insert(0, '('); + fmtValue.append(')'); + } + /* } else { + fmtValue = new StringBuffer("()"); + }*/ + return fmtValue.toString(); + } // formatListValue + + private String getColumnSelectStr(DataColumnType dc, ReportParamValues paramValues) { + String colName = dc.isCalculated() ? dc.getColName() + : ((nvl(dc.getTableId()).length() > 0) ? (dc.getTableId() + "." + dc + .getColName()) : dc.getColName()); + String paramValue = null; + if (dc.isCalculated()) + if (getFormFieldList() != null) + for (Iterator iter2 = getFormFieldList().getFormField().iterator(); iter2 + .hasNext();) { + FormFieldType fft = (FormFieldType) iter2.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = getFormFieldDisplayName(fft); + if (!paramValues.isParameterMultiValue(fieldId)) { + paramValue = paramValues.getParamValue(fieldId); + if(paramValue!=null && paramValue.length() > 0) { + colName = Utils.replaceInString(colName, fieldDisplay, Utils + .oracleSafe(nvl(paramValue, "NULL"))); + } else { + colName = Utils.replaceInString(colName, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + colName = Utils.replaceInString(colName, fieldDisplay, nvl( + paramValue, "NULL")); + } + } + } // for + + return colName; + } // getColumnSelectStr + + private void addExtraIdSelect(StringBuffer selectExtraIdCl, String drillDownParams, + boolean includeSelectExpr) { + // drillDownParams - example value "c_master=[bo1.RECID$]" + drillDownParams = drillDownParams.substring(10, drillDownParams.length() - 1); // i.e. + // "bo1.RECID$" + + selectExtraIdCl.append(", "); + if (includeSelectExpr) { + selectExtraIdCl.append(drillDownParams); + selectExtraIdCl.append(" "); + } // if + selectExtraIdCl.append(drillDownParams.replace('.', '_')); // i.e. + // "bo1_RECID$" + } // addExtraIdSelect + + private void addExtraDateSelect(StringBuffer selectExtraDateCl, String drillDownParams, + ReportParamValues paramValues, boolean includeSelectExpr) { + // drillDownParams - example value "ff1=[dl1]&fc2=[mo3]" + String colId = ""; + while (drillDownParams.indexOf('[') >= 0) { + int startIdx = drillDownParams.indexOf('['); + int endIdx = drillDownParams.indexOf(']'); + + if(startIdx<=endIdx) { + colId = drillDownParams.substring(startIdx + 1, endIdx); // i.e. + } else { + drillDownParams = drillDownParams.substring(endIdx + 1); + continue; + } + // "dl1" + + DataColumnType column = getColumnById(colId); + if (column != null) + if (column.getColType().equals(AppConstants.CT_DATE)) + if (!nvl(column.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT).equals( + AppConstants.DEFAULT_DATE_FORMAT)) + if (selectExtraDateCl.toString().indexOf( + " " + colId + AppConstants.DD_COL_EXTENSION) < 0) { + selectExtraDateCl.append(", "); + if (includeSelectExpr) { + selectExtraDateCl.append("TO_CHAR(" + + getColumnSelectStr(column, paramValues) + ", '" + + AppConstants.DEFAULT_DATE_FORMAT + "')"); + selectExtraDateCl.append(" "); + } // if + selectExtraDateCl.append(colId + AppConstants.DD_COL_EXTENSION); // i.e. + // "dl1_dde" + } // if + + drillDownParams = drillDownParams.substring(endIdx + 1); + } // while + } // addExtraDateSelect + + /* + * public String generateSQL() { return generateSQL(null); } // generateSQL + */ + public String generateSQL(String userId, HttpServletRequest request) throws RaptorException { + return generateSQL(new ReportParamValues(), userId, request); + } // generateSQL + + public String generateSQL(ReportParamValues paramValues, String userId, HttpServletRequest request) throws RaptorException { + return generateSQL(paramValues, null, AppConstants.SO_ASC, userId, request); + } // generateSQL + + public String generateSQL(ReportParamValues paramValues, String overrideSortByColId, + String overrideSortByAscDesc, String userId, HttpServletRequest request) throws RaptorException { + if (cr == null) + throw new NullPointerException("CustomReport not initialized"); + if(nvl(getWholeSQL()).length()>0) return getWholeSQL(); + if (paramValues.size() > 0) + resetCache(true); + //resetCache(true); + if (generatedSQL == null) { + if (getReportDefType().equals(AppConstants.RD_SQL_BASED) || getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN)) { + generatedSQL = generateSQLSQLBased(paramValues, overrideSortByColId, + overrideSortByAscDesc, userId, request ); + generatedChartSQL = generateSQLSQLBased(paramValues, null, + AppConstants.SO_ASC, userId, request ); + } else if (getReportDefType().equals(AppConstants.RD_VISUAL) && !getReportType().equals(AppConstants.RT_CROSSTAB)) { + generatedSQL = generateSQLVisual(paramValues, overrideSortByColId, + overrideSortByAscDesc, userId, request); + generatedChartSQL = generateSQLVisual(paramValues, null, + AppConstants.SO_ASC, userId, request); + } else { + generatedSQL = generateSQLCrossTabVisual(paramValues, overrideSortByColId, + overrideSortByAscDesc, userId, request); + } + + //debugLogger.debug("******************"); + //debugLogger.debug("SQL Before Changing new line \n" + generatedSQL); + //debugLogger.debug("******************"); + generatedSQL = replaceNewLine(generatedSQL, ""+ '\n', " "+'\n'+" " ); + //chart sql should not be null + if(nvl(generatedChartSQL).trim().length()>0) + generatedChartSQL = replaceNewLine(generatedChartSQL, ""+ '\n', " "+'\n'+" " ); + //(generatedSQL, "\n", " \n "); + //debugLogger.debug("******************"); + //debugLogger.debug("SQL After Changing new line \n" + generatedSQL); + //debugLogger.debug("******************"); + //generatedSQL = replaceNewLine(generatedSQL, "SELECT", "SELECT "); + //generatedSQL = replaceNewLine(generatedSQL, "select", "select "); + //debugLogger.debug("SQL After Changing new line \n" + generatedSQL); + //debugLogger.debug("[[[[[[[[[[[[[[[[[["); + //generatedSQL = Utils.replaceInString(generatedSQL, "\n", " "); + //generatedSQL = Utils.replaceInString(generatedSQL, "\t", " "); + } // if + + return generatedSQL; + } // generateSQL + + public String generateSQLSQLBased(ReportParamValues paramValues, + String overrideSortByColId, String overrideSortByAscDesc, String userId, HttpServletRequest request) throws RaptorException { + String sql = getReportSQL(); + DataSet ds = null; + //debugLogger.debug(" generateSQLSQLBased " + sql); + String[] reqParameters = Globals.getRequestParams().split(","); + String[] sessionParameters = Globals.getSessionParams().split(","); + String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(","); + javax.servlet.http.HttpSession session = request.getSession(); + String dbType = ""; + String dbInfo = getDBInfo(); + int fieldCount = 0; + // For Daytona removing all formfields which has null param value + Pattern re1 = null; + Matcher matcher = null; + int index = 0; + int posFormField = 0; + int posAnd = 0; + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + + sql = sql + " "; + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT "); + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" FROM "); + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE "); + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHEN "); + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND "); + + if (getFormFieldList() != null) { + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) { + + FormFieldType fft = (FormFieldType) iter.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = getFormFieldDisplayName(fft); + if(!fft.getFieldType().equals(FormField.FFT_BLANK)) { + if (paramValues.isParameterMultiValue(fieldId)) { + String replaceValue = formatListValue(fieldDisplay, Utils + .oracleSafe(nvl(paramValues.getParamValue(fieldId))), null, false, + true, null, paramValues.getParamBaseSQL(fieldId)); + if(replaceValue.length() > 0) { + sql = Utils.replaceInString(sql, fieldDisplay, replaceValue); + } else { + fieldCount++; + if(fieldCount == 1) { + //sql = sql + " "; + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT "); + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE "); + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND "); + } + //sql = getReportSQL(); + while(sql.indexOf(fieldDisplay) > 0) { +/* sql = Utils.replaceInString(sql, "SELECT ", "select "); + sql = Utils.replaceInString(sql, "WHERE", "where"); + sql = Utils.replaceInString(sql, " AND ", " and "); +*/ + re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); + //re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\]", Pattern.DOTALL); +/* posFormField = sql.indexOf(fieldDisplay); + posAnd = sql.lastIndexOf("and", posFormField); + if(posAnd < 0) posAnd = 0; + else if (posAnd > 2) posAnd = posAnd - 2; + matcher = re1.matcher(sql); +*/ + posFormField = sql.indexOf(fieldDisplay); + int posSelectField = sql.lastIndexOf("SELECT ", posFormField); + int andField = 0; + int whereField = 0, whenField = 0; + andField = sql.lastIndexOf(" AND ", posFormField); + whereField = sql.indexOf(" WHERE" , posSelectField); + whenField = sql.indexOf(" WHEN" , posSelectField); + + if(posFormField > whereField) + andField = sql.lastIndexOf(" AND ", posFormField); + if (posFormField > andField && (andField > whereField || andField > whenField)) + posAnd = andField; + else + posAnd = 0; + matcher = re1.matcher(sql); + + + if (posAnd > 0 && matcher.find(posAnd-1)) { + //sql = Utils.replaceInString(sql, matcher.group(), " "); + matcher = re1.matcher(sql); + index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1; + + if(andField>0) + index = andField; + else + index = whereField; + if(index >= 0 && matcher.find(index-1)) { + sql = sql.replace(matcher.group(), " "); + } + } else { + + //sql = sql.replace + re1 = Pattern.compile("(^[\r\n]|[\\s])WHERE(.*?[^\r\n]*)\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); + matcher = re1.matcher(sql); + if(whereField != -1) { + if(matcher.find(whereField-1)) { + matcher = re1.matcher(sql); + index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1; + if(index >= 0 && matcher.find(index-30)) { + sql = sql.replace(matcher.group(), " WHERE 1=1 "); + } + //sql = Utils.replaceInString(sql, matcher.group(), " where 1=1 "); + } /*else { + replaceValue = formatListValue("", Utils + .oracleSafe(nvl(paramValues.getParamValue(fieldId))), null, false, + true, null, paramValues.getParamBaseSQL(fieldId)); + sql = Utils.replaceInString(sql, fieldDisplay, replaceValue); + }*/ + } else { + sql = Utils.replaceInString(sql, fieldDisplay, replaceValue); + } + + } + } + } + + //sql = Utils.replaceInString(sql, " select ", " SELECT "); + //sql = Utils.replaceInString(sql, " where ", " WHERE "); + //sql = Utils.replaceInString(sql, " and ", " AND "); + + } else { + String paramValue = ""; + if(paramValues.isParameterTextAreaValueAndModified(fieldId)) { + String value = ""; + value = nvl(paramValues + .getParamValue(fieldId)); +// value = Utils.oracleSafe(nvl(value)); +// if (!(dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT"))) { +// value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; +// value = Utils.replaceInString(value, "|", ","); +// paramValue = XSSFilter.filterRequestOnlyScript(value); +// } else if (nvl(value.trim()).length()>0) { +// value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; +// value = Utils.replaceInString(value, "|", ","); +// paramValue = XSSFilter.filterRequestOnlyScript(value); +// } + paramValue = value; + } else + paramValue = Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId))); + + if (paramValue!=null && paramValue.length() > 0) { + if(paramValue.toLowerCase().trim().startsWith("select ")) { + paramValue = Utils.replaceInString(paramValue, "[LOGGED_USERID]", userId); + paramValue = Utils.replaceInString(paramValue, "[USERID]", userId); + paramValue = Utils.replaceInString(paramValue, "[USER_ID]", userId); + + paramValue = Utils.replaceInString(paramValue, "''", "'"); + ds = ConnectionUtils.getDataSet(paramValue, dbInfo); + if (ds.getRowCount() > 0) paramValue = ds.getString(0, 0); + } + //debugLogger.debug("SQLSQLBASED B4^^^^^^^^^ " + sql + " " + fft.getValidationType() + " " + fft.getFieldName() + " " + fft.getFieldId()); + if(fft!=null && (fft.getValidationType()!=null && (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) ||fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ||fft.getValidationType().equals(FormField.VT_DATE) ))) { + //System.out.println("paramValues.getParamValue(fieldId_Hr) Inside if " + fft.getValidationType() + " " + fieldDisplay); + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue) +((nvl(paramValues + .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ) ):"")); + } + else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) { +/* System.out.println("paramValues.getParamValue(fieldId_Hr)" + paramValues + .getParamValue(fieldId+"_Hr") + " " + paramValues + .getParamValue(fieldId+"_Min")) ; +*/ sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue) + ((nvl(paramValues + .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ) ):"") + ((nvl(paramValues + .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Min") ) ) ) : "") ) ; + } + else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue) + ((nvl(paramValues + .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ) ):"") + ((nvl(paramValues + .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Min") ) ) ) : "") + ((nvl(paramValues + .getParamValue(fieldId+"_Sec") ).length()>0)?":"+addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Sec") ) ) ) : "" ) ) ; + } else { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } + + + } else { + if(paramValue!=null && paramValue.length() > 0) { + if(sql.indexOf("'"+fieldDisplay+"'")!=-1 || sql.indexOf("'"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"'")!=-1 + || sql.indexOf("'%"+fieldDisplay+"%'")!=-1 || sql.indexOf("'%"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"%'")!=-1 + || sql.indexOf("'_"+fieldDisplay+"_'")!=-1 || sql.indexOf("'_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_'")!=-1 + || sql.indexOf("'%_"+fieldDisplay+"_%'")!=-1 || sql.indexOf("^"+fieldDisplay+"^")!=-1 || sql.indexOf("'%_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_%'")!=-1) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } else { + if(sql.indexOf(fieldDisplay)!=-1) { + if(nvl(paramValue).length()>0) { + try { + double vD = Double.parseDouble(paramValue); + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + + } catch (NumberFormatException ex) { + if (/*dbType.equals("DAYTONA") &&*/ sql.trim().toUpperCase().startsWith("SELECT")) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } else + throw new UserDefinedException("Expected number, Given String for the form field \"" + fieldDisplay+"\""); + } + /*sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL"));*/ + } else + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + + } + } + } + else { + if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) { + sql = sql + " "; + re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); + posFormField = sql.indexOf(fieldDisplay); + posAnd = sql.lastIndexOf(" AND ", posFormField); + if(posAnd < 0) posAnd = 0; + else if (posAnd > 2) posAnd = posAnd - 2; + matcher = re1.matcher(sql); + if (matcher.find(posAnd)) { + sql = sql.replace(matcher.group(), ""); + } + } else { + sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } + } + } + + } + + if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) { + sql = sql + " "; + re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); //+[\'\\)|\'|\\s] + posFormField = sql.indexOf(fieldDisplay); + posAnd = sql.lastIndexOf(" AND ", posFormField); + if(posAnd < 0) posAnd = 0; + else if (posAnd > 2) posAnd = posAnd - 2; + matcher = re1.matcher(sql); + if (matcher.find(posAnd)) { + sql = sql.replace(matcher.group(), " "); + } + } else { + if( fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) { + sql = Pattern.compile("[[\\s*][,]]\\["+fft.getFieldName()+"\\](.*?)[,]",Pattern.MULTILINE).matcher(sql).replaceAll(" "); + //sql = Pattern.compile("[,][\\s*]\\["+fft.getFieldName()+"\\][\\s]",Pattern.MULTILINE).matcher(sql).replaceAll(" "); + sql = Pattern.compile("(,.+?)[\\s*]\\["+fft.getFieldName()+"\\][\\s]",Pattern.MULTILINE).matcher(sql).replaceAll(" "); + //sql = Pattern.compile("(?:,?)[\\s*]\\["+fft.getFieldName()+"\\]",Pattern.MULTILINE).matcher(sql).replaceAll(""); + //sql = Pattern.compile("[,][\\s*]\\["+fft.getFieldName()+"\\]",Pattern.MULTILINE).matcher(sql).replaceAll(" "); + //sql = Pattern.compile( "\\["+fft.getFieldName()+"\\](.*?[^\r\n]*)[,]",Pattern.DOTALL).matcher(sql).replaceAll(""); + + //sql = Pattern.compile("[,]|(.*?[^\r\n]*)"+fieldDisplay+"(.*?)\\s",Pattern.DOTALL).matcher(sql).replaceAll(""); + //sql = Pattern.compile("(.*?[^\r\n]*)"+fieldDisplay+"(.*?)\\s|[,]",Pattern.DOTALL).matcher(sql).replaceAll(""); +/* sql = Utils.replaceInString(sql, "," + fieldDisplay , nvl( + paramValue, "")); + sql = Utils.replaceInString(sql, fieldDisplay + "," , nvl( + paramValue, "")); +*/ } else { + //debugLogger.debug("ParamValue |" + paramValue + "| Sql |" + sql + "| Multi Value |" + paramValues.isParameterMultiValue(fieldId)); + sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + sql = Utils.replaceInString(sql, fieldDisplay , nvl( + paramValue, "NULL")); + //debugLogger.debug("SQLSQLBASED AFTER^^^^^^^^^ " + sql); + } + } + + } // else + } // if BLANK + } // for + if(request != null ) { + for (int i = 0; i < reqParameters.length; i++) { + if(!reqParameters[i].startsWith("ff")) { + if (nvl(request.getParameter(reqParameters[i].toUpperCase())).length() > 0) + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) ); + } + else + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) ); + } + + for (int i = 0; i < scheduleSessionParameters.length; i++) { + if(nvl(request.getParameter(scheduleSessionParameters[i])).trim().length()>0 ) + sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) ); + } + } + if(session != null ) { + for (int i = 0; i < sessionParameters.length; i++) { + //if(!sessionParameters[i].startsWith("ff")) + // paramValue = Utils.replaceInString(paramValue, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); + // else { + //debugLogger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])); + sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + //} + } + } + } else { + //debugLogger.debug("BEFORE LOGGED USERID REPLACE " + sql); + //sql = Utils.replaceInString(sql, "'[logged_userId]'", "'"+userId+"'"); + //debugLogger.debug("Replacing string 2 " + sql); + sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId); + sql = Utils.replaceInString(sql, "[USERID]", userId); + sql = Utils.replaceInString(sql, "[USER_ID]", userId); + //debugLogger.debug("AFTER LOGGED USERID REPLACE " + sql); + // Added for Simon's GM Project where they need to get page_id in their query + //debugLogger.debug("SQLSQLBASED no formfields " + sql); + if(request != null ) { + for (int i = 0; i < reqParameters.length; i++) { + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) ); + } + } + if(session != null ) { + for (int i = 0; i < sessionParameters.length; i++) { + //debugLogger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])); + sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + } + } + } + // if it is not multiple select and ParamValue is empty this is the place it can be replaced. + sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId); + sql = Utils.replaceInString(sql, "[USERID]", userId); + sql = Utils.replaceInString(sql, "[USER_ID]", userId); + //debugLogger.debug("SQLSQLBASED no formfields after" + sql); + //debugLogger.debug("Replacing String 2 "+ sql); + //debugLogger.debug("Replaced String " + sql); + + int closeBracketPos = 0; + if (nvl(overrideSortByColId).length() > 0) { + if(sql.lastIndexOf(")")!= -1) closeBracketPos = sql.lastIndexOf(")"); + int idxOrderBy = (closeBracketPos>0)?sql.toUpperCase().indexOf("ORDER BY", closeBracketPos):sql.toUpperCase().lastIndexOf("ORDER BY"); + DataColumnType dct = getColumnById(overrideSortByColId+"_sort"); + if(dct!=null && dct.getColName().length()>0) { + overrideSortByColId = overrideSortByColId+"_sort"; + } + if (idxOrderBy < 0) + sql += " ORDER BY " + overrideSortByColId + " " + overrideSortByAscDesc; + else { + int braketCount = 0; + int idxOrderByClauseEnd = 0; + for (idxOrderByClauseEnd = idxOrderBy; idxOrderByClauseEnd < sql.length(); idxOrderByClauseEnd++) { + char ch = sql.charAt(idxOrderByClauseEnd); + + if (ch == '(') + braketCount++; + else if (ch == ')') { + if (braketCount == 0) + break; + braketCount--; + } + } // for + + sql = sql.substring(0, idxOrderBy) + " ORDER BY " + overrideSortByColId + " " + + overrideSortByAscDesc + sql.substring(idxOrderByClauseEnd); + } // else + } // if + sql = Pattern.compile("([\n][\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" "); + return sql; + } // generateSQLSQLBased + + public String generateSQLVisual(ReportParamValues paramValues, String overrideSortByColId, + String overrideSortByAscDesc, String userId, HttpServletRequest request)throws RaptorException { + StringBuffer selectCl = new StringBuffer(); + StringBuffer fromCl = new StringBuffer(); + StringBuffer whereCl = new StringBuffer(); + StringBuffer groupByCl = new StringBuffer(); + StringBuffer havingCl = new StringBuffer(); + StringBuffer orderByCl = new StringBuffer(); + StringBuffer selectExtraIdCl = new StringBuffer(); + StringBuffer selectExtraDateCl = new StringBuffer(); + + int whereClBracketCount = 0; + int havingClBracketCount = 0; + int whereClCarryoverBrackets = 0; + int havingClCarryoverBrackets = 0; + + // Identifying FROM clause tables and WHERE clause joins + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + + if (fromCl.length() > 0) + fromCl.append(", "); + fromCl.append(ds.getTableName()); + fromCl.append(" "); + fromCl.append(ds.getTableId()); + + if (nvl(ds.getRefTableId()).length() > 0) { + if (whereCl.length() > 0) + whereCl.append(" AND "); + whereCl.append(ds.getRefDefinition()); + } // if + // Add the condition. + TableSource tableSource = null; + String dBInfo = this.cr.getDbInfo(); + Vector userRoles = AppUtils.getUserRoles(request); + tableSource = DataCache.getTableSource(ds.getTableName(), dBInfo,userRoles,userId, request); + if (userId != null && (!AppUtils.isSuperUser(request)) + && (!AppUtils.isAdminUser(request)) && tableSource != null + && nvl(tableSource.getFilterSql()).length() > 0) { + if (whereCl.length() > 0) + whereCl.append(" AND "); + whereCl.append(Utils.replaceInString(Utils.replaceInString(tableSource + .getFilterSql(), "[" + ds.getTableName() + "]", ds.getTableId()), + "[USER_ID]", userId)); + } // if + } // for + + List reportCols = getAllColumns(); + + boolean isGroupStmt = false; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.isGroupBreak()) { + isGroupStmt = true; + break; + } // if + } // for + + // Identifying SELECT and GROUP BY clause fields and WHERE and HAVING + // clause filters + // Collections.sort(reportCols, new OrderSeqComparator()); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + + // SELECT clause fields + //TODO: Uncomment if it's not working -- if (dc.isVisible()) { + if (selectCl.length() > 0) + selectCl.append(", "); + selectCl.append(getSelectExpr(dc, colName)); + selectCl.append(" "); + selectCl.append(dc.getColId()); + //TODO } // if + + // Checking for extra fields necessary for drill-down + if (nvl(dc.getDrillDownURL()).length() > 0) + if (isViewAction(dc.getDrillDownURL())) + addExtraIdSelect(selectExtraIdCl, nvl(dc.getDrillDownParams()), true); + else + addExtraDateSelect(selectExtraDateCl, nvl(dc.getDrillDownParams()), + paramValues, true); + + // GROUP BY clause fields + if (dc.isGroupBreak()) { + if (groupByCl.length() > 0) + groupByCl.append(", "); + groupByCl.append(colName); + } // if + + // WHERE/HAVING clause fields + //boolean isHavingCl = isGroupStmt && dc.isVisible() && (!dc.isGroupBreak()); + boolean isHavingCl = isGroupStmt && (!dc.isGroupBreak()); + StringBuffer filterCl = isHavingCl ? havingCl : whereCl; + // StringBuffer filterCl = + // isGroupStmt?(dc.isVisible()?(dc.isGroupBreak()?whereCl:havingCl):whereCl):whereCl; + if (dc.getColFilterList() != null) { + int fNo = 0; + List fList = dc.getColFilterList().getColFilter(); + for (Iterator iterF = fList.iterator(); iterF.hasNext(); fNo++) { + ColFilterType cf = (ColFilterType) iterF.next(); + + StringBuffer curFilter = new StringBuffer(); + if (filterCl.length() > 0) + curFilter.append(" " + cf.getJoinCondition() + " "); + if ((isHavingCl ? havingClCarryoverBrackets : whereClCarryoverBrackets) > 0) + for (int b = 0; b < (isHavingCl ? havingClCarryoverBrackets + : whereClCarryoverBrackets); b++) + filterCl.append('('); + curFilter.append(nvl(cf.getOpenBrackets())); + curFilter.append(colName + " "); + curFilter.append(cf.getExpression() + " "); + + boolean applyFilter = true; + if ((nvl(cf.getArgValue()).length() > 0) + || (nvl(cf.getArgType()).equals(AppConstants.AT_FORM))) + if (nvl(cf.getArgType()).equals(AppConstants.AT_FORMULA)) + curFilter.append(cf.getArgValue()); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_VALUE)) + curFilter.append(formatValue(cf.getArgValue(), dc, false)); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_LIST)) + curFilter.append(formatListValue(cf.getArgValue(), dc, false, + false)); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_COLUMN)) + curFilter.append(getColumnNameById(cf.getArgValue())); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_FORM)) { + String fieldName = getFormFieldName(cf); + String fieldValue = Utils.oracleSafe(paramValues + .getParamValue(fieldName)); + boolean isMultiValue = paramValues + .isParameterMultiValue(fieldName); + boolean usePipeDelimiterOnly = false; + + FormFieldType fft = getFormFieldByDisplayValue(cf.getArgValue()); + if (fft == null) + // If not FormField => applying default value + fieldValue = nvl(fieldValue, Utils + .oracleSafe(cf.getArgValue())); + else + usePipeDelimiterOnly = fft.getFieldType().equals( + FormField.FFT_CHECK_BOX) + || fft.getFieldType().equals(FormField.FFT_LIST_MULTI); + //Added for TimeStamp validation + String fieldId = fft.getFieldId(); + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)||fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { + fieldValue = nvl( + fieldValue + " " + addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ) ) ) ; + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { + fieldValue = fieldValue + (nvl(paramValues + .getParamValue(fieldId+"_Min")).length()>0 ? ":" + addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Min")))): "") ; + } + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { + fieldValue = fieldValue + (nvl(paramValues + .getParamValue(fieldId+"_Sec")).length()>0 ? ":"+ addZero(Utils.oracleSafe(nvl(paramValues + .getParamValue(fieldId+"_Sec")))) : ""); + } + } + + // End + if (nvl(fieldValue).length() == 0) + // Does not append filter with missing form + // field argument + applyFilter = false; + else if (isMultiValue || nvl(cf.getExpression()).equals("IN") + || nvl(cf.getExpression()).equals("NOT IN")) + curFilter.append(formatListValue(fieldValue, dc, true, + usePipeDelimiterOnly)); + else + curFilter.append(formatValue(fieldValue, dc, true, null, fft)); + } // else + curFilter.append(nvl(cf.getCloseBrackets())); + + if (applyFilter) { + filterCl.append(curFilter.toString()); + + if (isHavingCl) { + havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + havingClCarryoverBrackets = 0; + } else { + whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + whereClCarryoverBrackets = 0; + } + } else if (nvl(cf.getOpenBrackets()).length() != nvl(cf.getCloseBrackets()) + .length()) + if (nvl(cf.getOpenBrackets()).length() > nvl(cf.getCloseBrackets()) + .length()) { + // Carry over opening brackets + if (isHavingCl) + havingClCarryoverBrackets += (nvl(cf.getOpenBrackets()) + .length() - nvl(cf.getCloseBrackets()).length()); + else + whereClCarryoverBrackets += (nvl(cf.getOpenBrackets()) + .length() - nvl(cf.getCloseBrackets()).length()); + + if (isHavingCl) + havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + else + whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + } else { + // Adding closing brackets + if (filterCl.length() > 0) { + for (int b = 0; b < nvl(cf.getCloseBrackets()).length() + - nvl(cf.getOpenBrackets()).length(); b++) + filterCl.append(')'); + + if (isHavingCl) + havingClBracketCount += (nvl(cf.getOpenBrackets()) + .length() - nvl(cf.getCloseBrackets()).length()); + else + whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + } // if + } // else + } // for + } // if + } // for + + // Identifying ORDER BY clause fields + DataColumnType overrideSortByCol = null; + if (overrideSortByColId != null) + overrideSortByCol = getColumnById(overrideSortByColId); + + if (overrideSortByCol != null) { + orderByCl.append(getColumnSelectStr(overrideSortByCol, paramValues)); + orderByCl.append(" "); + orderByCl.append(nvl(overrideSortByAscDesc, AppConstants.SO_ASC)); + } else if (getReportType().equals(AppConstants.RT_CROSSTAB)) { + /* + * for(Iterator iter=reportCols.iterator(); iter.hasNext(); ) { + * DataColumnType dc = (DataColumnType) iter.next(); + * + * if(nvl(dc.getCrossTabValue()).equals(AppConstants.CV_ROW)||nvl(dc.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) { + * if(orderByCl.length()>0) orderByCl.append(", "); + * orderByCl.append(getColumnSelectStr(dc, paramValues)); + * orderByCl.append(" "); + * if(dc.getColType().equals(AppConstants.CT_DATE)) + * orderByCl.append(AppConstants.SO_DESC); else + * orderByCl.append(AppConstants.SO_ASC); } // if } // for + */ + } else { + Collections.sort(reportCols, new OrderBySeqComparator()); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + + if (dc.getOrderBySeq() > 0) { + if (orderByCl.length() > 0) + orderByCl.append(", "); + orderByCl.append(getColumnSelectStr(dc, paramValues)); + orderByCl.append(" "); + orderByCl.append(dc.getOrderByAscDesc()); + } // if + } // for + Collections.sort(reportCols, new OrderSeqComparator()); + } // else + + // Adding up the actual statement + StringBuffer sql = new StringBuffer(); + //sql.append("SELECT "); // Need to add PK for /*+ FIRST_ROWS */ "); + sql.append(Globals.getGenerateSqlVisualSelect()); + //sql.append((selectCl.length() == 0) ? "COUNT(*) cnt" : selectCl.toString()); + sql.append((selectCl.length() == 0) ? Globals.getGenerateSqlVisualCount() : selectCl.toString()); + if (groupByCl.length() == 0) + sql.append(selectExtraIdCl.toString()); + sql.append(selectExtraDateCl.toString()); + // sql.append(" FROM "); + sql.append((fromCl.length() == 0) ? Globals.getGenerateSqlVisualDual() : "FROM "+fromCl.toString()); + if (whereCl.length() > 0) { + if (whereClBracketCount > 0) { + for (int b = 0; b < whereClBracketCount; b++) + whereCl.append(')'); + } else if (whereClBracketCount < 0) { + for (int b = 0; b < Math.abs(whereClBracketCount); b++) + whereCl.insert(0, '('); + } // else + + sql.append(" WHERE "); + sql.append(whereCl.toString()); + } // if + if (groupByCl.length() > 0) { + sql.append(" GROUP BY "); + sql.append(groupByCl.toString()); + + if (havingCl.length() > 0) { + if (havingClBracketCount > 0) { + for (int b = 0; b < havingClBracketCount; b++) + havingCl.append(')'); + } else if (havingClBracketCount < 0) { + for (int b = 0; b < Math.abs(havingClBracketCount); b++) + havingCl.insert(0, '('); + } // else + + sql.append(" HAVING "); + sql.append(havingCl.toString()); + } + } + if (orderByCl.length() > 0) { + sql.append(" ORDER BY "); + sql.append(orderByCl.toString()); + } + //String sqlStr = Utils.replaceInString(sql.toString(), "[LOGGED_USERID]", userId); + //return sqlStr; + return sql.toString(); + } // generateSQLVisual + + public String generateSQLCrossTabVisual(ReportParamValues paramValues, String overrideSortByColId, + String overrideSortByAscDesc, String userId, HttpServletRequest request) throws RaptorException { + StringBuffer selectCl = new StringBuffer(); + StringBuffer fromCl = new StringBuffer(); + StringBuffer whereCl = new StringBuffer(); + StringBuffer groupByCl = new StringBuffer(); + StringBuffer havingCl = new StringBuffer(); + StringBuffer orderByCl = new StringBuffer(); + StringBuffer selectExtraIdCl = new StringBuffer(); + StringBuffer selectExtraDateCl = new StringBuffer(); + + int whereClBracketCount = 0; + int havingClBracketCount = 0; + int whereClCarryoverBrackets = 0; + int havingClCarryoverBrackets = 0; + + // Identifying FROM clause tables and WHERE clause joins + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + + if (fromCl.length() > 0) + fromCl.append(", "); + fromCl.append(ds.getTableName()); + fromCl.append(" "); + fromCl.append(ds.getTableId()); + + if (nvl(ds.getRefTableId()).length() > 0) { + if (whereCl.length() > 0) + whereCl.append(" AND "); + whereCl.append(ds.getRefDefinition()); + } // if + // Add the condition. + TableSource tableSource = null; + String dBInfo = this.cr.getDbInfo(); + Vector userRoles = AppUtils.getUserRoles(request); + tableSource = DataCache.getTableSource(ds.getTableName(), dBInfo,userRoles,userId, request); + if (userId != null && (!AppUtils.isSuperUser(request)) + && (!AppUtils.isAdminUser(request)) && tableSource != null + && nvl(tableSource.getFilterSql()).length() > 0) { + if (whereCl.length() > 0) + whereCl.append(" AND "); + whereCl.append(Utils.replaceInString(Utils.replaceInString(tableSource + .getFilterSql(), "[" + ds.getTableName() + "]", ds.getTableId()), + "[USER_ID]", userId)); + } // if + } // for + + List reportCols = getAllColumns(); + + boolean isGroupStmt = false; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.isGroupBreak()) { + isGroupStmt = true; + break; + } // if + } // for + + // Identifying SELECT and GROUP BY clause fields and WHERE and HAVING + // clause filters + // Collections.sort(reportCols, new OrderSeqComparator()); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + + // SELECT clause fields + if (dc.isVisible()) { + if (selectCl.length() > 0) + selectCl.append(", "); + selectCl.append(getSelectExpr(dc, colName)); + selectCl.append(" "); + selectCl.append(dc.getColId()); + } // if + + // Checking for extra fields necessary for drill-down + if (nvl(dc.getDrillDownURL()).length() > 0) + if (isViewAction(dc.getDrillDownURL())) + addExtraIdSelect(selectExtraIdCl, nvl(dc.getDrillDownParams()), true); + else + addExtraDateSelect(selectExtraDateCl, nvl(dc.getDrillDownParams()), + paramValues, true); + + // GROUP BY clause fields + if (dc.isGroupBreak()) { + if (groupByCl.length() > 0) + groupByCl.append(", "); + groupByCl.append(colName); + } // if + + // WHERE/HAVING clause fields + boolean isHavingCl = isGroupStmt && dc.isVisible() && (!dc.isGroupBreak()); + //boolean isHavingCl = isGroupStmt && (!dc.isGroupBreak()); + //StringBuffer filterCl = isHavingCl ? havingCl : whereCl; + StringBuffer filterCl = + isGroupStmt?(dc.isVisible()?(dc.isGroupBreak()?whereCl:havingCl):whereCl):whereCl; + if (dc.getColFilterList() != null) { + int fNo = 0; + List fList = dc.getColFilterList().getColFilter(); + for (Iterator iterF = fList.iterator(); iterF.hasNext(); fNo++) { + ColFilterType cf = (ColFilterType) iterF.next(); + + StringBuffer curFilter = new StringBuffer(); + if (filterCl.length() > 0) + curFilter.append(" " + cf.getJoinCondition() + " "); + if ((isHavingCl ? havingClCarryoverBrackets : whereClCarryoverBrackets) > 0) + for (int b = 0; b < (isHavingCl ? havingClCarryoverBrackets + : whereClCarryoverBrackets); b++) + filterCl.append('('); + curFilter.append(nvl(cf.getOpenBrackets())); + curFilter.append(colName + " "); + curFilter.append(cf.getExpression() + " "); + + boolean applyFilter = true; + if ((nvl(cf.getArgValue()).length() > 0) + || (nvl(cf.getArgType()).equals(AppConstants.AT_FORM))) + if (nvl(cf.getArgType()).equals(AppConstants.AT_FORMULA)) + curFilter.append(cf.getArgValue()); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_VALUE)) + curFilter.append(formatValue(cf.getArgValue(), dc, false)); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_LIST)) + curFilter.append(formatListValue(cf.getArgValue(), dc, false, + false)); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_COLUMN)) + curFilter.append(getColumnNameById(cf.getArgValue())); + else if (nvl(cf.getArgType()).equals(AppConstants.AT_FORM)) { + String fieldName = getFormFieldName(cf); + String fieldValue = Utils.oracleSafe(paramValues + .getParamValue(fieldName)); + boolean isMultiValue = paramValues + .isParameterMultiValue(fieldName); + boolean usePipeDelimiterOnly = false; + + FormFieldType fft = getFormFieldByDisplayValue(cf.getArgValue()); + if (fft == null) + // If not FormField => applying default value + fieldValue = nvl(fieldValue, Utils + .oracleSafe(cf.getArgValue())); + else + usePipeDelimiterOnly = fft.getFieldType().equals( + FormField.FFT_CHECK_BOX) + || fft.getFieldType().equals(FormField.FFT_LIST_MULTI); + + if (nvl(fieldValue).length() == 0) + // Does not append filter with missing form + // field argument + applyFilter = false; + else if (isMultiValue || nvl(cf.getExpression()).equals("IN") + || nvl(cf.getExpression()).equals("NOT IN")) + curFilter.append(formatListValue(fieldValue, dc, true, + usePipeDelimiterOnly)); + else + curFilter.append(formatValue(fieldValue, dc, true)); + } // else + curFilter.append(nvl(cf.getCloseBrackets())); + + if (applyFilter) { + filterCl.append(curFilter.toString()); + + if (isHavingCl) { + havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + havingClCarryoverBrackets = 0; + } else { + whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + whereClCarryoverBrackets = 0; + } + } else if (nvl(cf.getOpenBrackets()).length() != nvl(cf.getCloseBrackets()) + .length()) + if (nvl(cf.getOpenBrackets()).length() > nvl(cf.getCloseBrackets()) + .length()) { + // Carry over opening brackets + if (isHavingCl) + havingClCarryoverBrackets += (nvl(cf.getOpenBrackets()) + .length() - nvl(cf.getCloseBrackets()).length()); + else + whereClCarryoverBrackets += (nvl(cf.getOpenBrackets()) + .length() - nvl(cf.getCloseBrackets()).length()); + + if (isHavingCl) + havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + else + whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + } else { + // Adding closing brackets + if (filterCl.length() > 0) { + for (int b = 0; b < nvl(cf.getCloseBrackets()).length() + - nvl(cf.getOpenBrackets()).length(); b++) + filterCl.append(')'); + + if (isHavingCl) + havingClBracketCount += (nvl(cf.getOpenBrackets()) + .length() - nvl(cf.getCloseBrackets()).length()); + else + whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl( + cf.getCloseBrackets()).length()); + } // if + } // else + } // for + } // if + } // for + + // Identifying ORDER BY clause fields + DataColumnType overrideSortByCol = null; + if (overrideSortByColId != null) + overrideSortByCol = getColumnById(overrideSortByColId); + + if (overrideSortByCol != null) { + orderByCl.append(getColumnSelectStr(overrideSortByCol, paramValues)); + orderByCl.append(" "); + orderByCl.append(nvl(overrideSortByAscDesc, AppConstants.SO_ASC)); + } else if (getReportType().equals(AppConstants.RT_CROSSTAB)) { + /* + * for(Iterator iter=reportCols.iterator(); iter.hasNext(); ) { + * DataColumnType dc = (DataColumnType) iter.next(); + * + * if(nvl(dc.getCrossTabValue()).equals(AppConstants.CV_ROW)||nvl(dc.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) { + * if(orderByCl.length()>0) orderByCl.append(", "); + * orderByCl.append(getColumnSelectStr(dc, paramValues)); + * orderByCl.append(" "); + * if(dc.getColType().equals(AppConstants.CT_DATE)) + * orderByCl.append(AppConstants.SO_DESC); else + * orderByCl.append(AppConstants.SO_ASC); } // if } // for + */ + } else { + Collections.sort(reportCols, new OrderBySeqComparator()); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + + if (dc.getOrderBySeq() > 0) { + if (orderByCl.length() > 0) + orderByCl.append(", "); + orderByCl.append(getColumnSelectStr(dc, paramValues)); + orderByCl.append(" "); + orderByCl.append(dc.getOrderByAscDesc()); + } // if + } // for + Collections.sort(reportCols, new OrderSeqComparator()); + } // else + + // Adding up the actual statement + StringBuffer sql = new StringBuffer(); + //sql.append("SELECT "); // Need to add PK for /*+ FIRST_ROWS */ "); + sql.append(Globals.getGenerateSqlVisualSelect()); + // sql.append((selectCl.length() == 0) ? "COUNT(*) cnt" : selectCl.toString()); + sql.append((selectCl.length() == 0) ? Globals.getGenerateSqlVisualCount() : selectCl.toString()); + if (groupByCl.length() == 0) + sql.append(selectExtraIdCl.toString()); + sql.append(selectExtraDateCl.toString()); + // sql.append(" FROM "); + sql.append((fromCl.length() == 0) ? Globals.getGenerateSqlVisualDual() : "FROM "+fromCl.toString()); + if (whereCl.length() > 0) { + if (whereClBracketCount > 0) { + for (int b = 0; b < whereClBracketCount; b++) + whereCl.append(')'); + } else if (whereClBracketCount < 0) { + for (int b = 0; b < Math.abs(whereClBracketCount); b++) + whereCl.insert(0, '('); + } // else + + sql.append(" WHERE "); + sql.append(whereCl.toString()); + } // if + if (groupByCl.length() > 0) { + sql.append(" GROUP BY "); + sql.append(groupByCl.toString()); + + if (havingCl.length() > 0) { + if (havingClBracketCount > 0) { + for (int b = 0; b < havingClBracketCount; b++) + havingCl.append(')'); + } else if (havingClBracketCount < 0) { + for (int b = 0; b < Math.abs(havingClBracketCount); b++) + havingCl.insert(0, '('); + } // else + + sql.append(" HAVING "); + sql.append(havingCl.toString()); + } + } + if (orderByCl.length() > 0) { + sql.append(" ORDER BY "); + sql.append(orderByCl.toString()); + } + + System.out.println("Created SQL statement: "+sql); + + //String sqlStr = Utils.replaceInString(sql.toString(), "[LOGGED_USERID]", userId); + //return sqlStr; + return sql.toString(); + } // generateSQLCrossTabVisual + + + public String generatePagedSQL(int pageNo, String userId, HttpServletRequest request, boolean getColumnNamesFromReportSQL, ReportParamValues paramValues) throws RaptorException { + int counter = 0; + if(!Globals.isMySQL()) + counter = 1; + return generateSubsetSQL(pageNo * getPageSize() + counter, ((pageNo + 1) * getPageSize()) + + ((pageNo == 0) ? 1 : 0), userId, request, getColumnNamesFromReportSQL, paramValues); + } // generatePagedSQL + + public String generateSubsetSQL(int startRow, int endRow, String userId, HttpServletRequest request, boolean getColumnNamesFromReportSQL, ReportParamValues paramValues) throws RaptorException { + //debugLogger.debug(" ******** End Row ********* " + endRow); + String dbInfo = getDBInfo(); + String dbType = ""; + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + List reportCols = getAllColumns(); + String wholeSQL_OrderBy = getWholeSQL(); + String reportSQL = getWholeSQL(); + reportSQL = reportSQL.replace(";", ""); + setWholeSQL(reportSQL); + if(nvl(reportSQL).length()>0) + reportSQL = generateSQL(userId, request); + + if (reportSQL.toUpperCase().indexOf("ORDER BY ") < 0) { + StringBuffer sortBy = null; + + if (reportSQL.toUpperCase().indexOf("GROUP BY ") < 0) + if (getDataSourceList().getDataSource().size() > 0) { + DataSourceType dst = (DataSourceType) getDataSourceList().getDataSource() + .get(0); + String tId = dst.getTableId(); + String tPK = dst.getTablePK(); + if (nvl(tPK).length() > 0) { + sortBy = new StringBuffer(); + StringTokenizer st = new StringTokenizer(tPK, ", "); + while (st.hasMoreTokens()) { + if (sortBy.length() > 0) + sortBy.append(","); + sortBy.append(tId); + sortBy.append("."); + sortBy.append(st.nextToken()); + } // while + } + } // if + if (reportSQL.trim().toUpperCase().startsWith("SELECT")) { + //if (!(dbType.equals("DAYTONA") && reportSQL.trim().toUpperCase().startsWith("SELECT"))) + // reportSQL += " ORDER BY " + ((sortBy == null) ? "1" : sortBy.toString()); + } + } + + StringBuffer colNames = new StringBuffer(); + StringBuffer colExtraIdNames = new StringBuffer(); + StringBuffer colExtraDateNames = new StringBuffer(); + + if(getColumnNamesFromReportSQL) { + DataSet ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); + List reportCols1 = getAllColumns(); + reportCols = new Vector(); + outer: + for (Iterator iter = reportCols1.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + for (int k=0; k 0) + colNames.append(", "); + colNames.append(dc.getColId()); + //TODO uncomment if it's not working} // if + + // Checking for extra fields necessary for drill-down + if (nvl(dc.getDrillDownURL()).length() > 0) + if (isViewAction(dc.getDrillDownURL())) + addExtraIdSelect(colExtraIdNames, nvl(dc.getDrillDownParams()), false); + else + addExtraDateSelect(colExtraDateNames, nvl(dc.getDrillDownParams()), null, + false); + } // for + + if (reportSQL.toUpperCase().indexOf("GROUP BY ") < 0) + colNames.append(colExtraIdNames.toString()); + //commented to avoid coldId_dde + //colNames.append(colExtraDateNames.toString()); + + /* + * if(pageNo==0) if(reportSQL.toUpperCase().indexOf(" WHERE ")<0) + * if(reportSQL.toUpperCase().indexOf(" GROUP BY ")<0) reportSQL = + * reportSQL.substring(0, reportSQL.toUpperCase().indexOf(" ORDER BY + * "))+" WHERE ROWNUM <= + * "+getPageSize()+reportSQL.substring(reportSQL.toUpperCase().indexOf(" + * ORDER BY ")); else reportSQL = "SELECT "+colNames.toString()+" FROM + * (SELECT ROWNUM rnum, "+colNames.toString()+" FROM ("+reportSQL+") x) + * y WHERE rnum <= "+getPageSize()+" ORDER BY rnum"; else reportSQL = + * reportSQL.substring(0, reportSQL.toUpperCase().indexOf(" WHERE "))+" + * WHERE ROWNUM <= "+getPageSize()+" AND + * "+reportSQL.substring(reportSQL.toUpperCase().indexOf(" WHERE ")+7); + * else reportSQL = "SELECT "+colNames.toString()+" FROM (SELECT ROWNUM + * rnum, "+colNames.toString()+" FROM ("+reportSQL+") x) y WHERE rnum >= + * "+(pageNo*getPageSize()+1)+" AND rnum <= + * "+((pageNo+1)*getPageSize())+" ORDER BY rnum"; + */ + if (dbType.equals("DAYTONA") && reportSQL.trim().toUpperCase().startsWith("SELECT")) { + if(endRow == -1) endRow = (getMaxRowsInExcelDownload()>0)?getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + reportSQL = reportSQL + " LIMIT TO " +(startRow==0?startRow+1:startRow)+"->"+endRow; + return reportSQL; + } else if (dbType.equals("DAYTONA")) { + return reportSQL; + } + + //reportSQL = "SELECT " + colNames.toString() + " FROM (SELECT ROWNUM rnum, " + // + colNames.toString() + " FROM (" + reportSQL + ") x "; + + String rSQL = Globals.getGenerateSubsetSql(); + rSQL = rSQL.replace("[colNames.toString()]", colNames.toString()); + rSQL = rSQL.replace("[reportSQL]", reportSQL); + + reportSQL=rSQL; + //added rownum for total report where row header need to be shown + //reportSQLOnlyFirstPart = "SELECT rnum," + colNames.toString() + " FROM (SELECT ROWNUM rnum, " + //+ colNames.toString() + " FROM (" ; + + reportSQLOnlyFirstPart = Globals.getReportSqlOnlyFirstPart(); + reportSQLOnlyFirstPart = reportSQLOnlyFirstPart.replace("[colNames.toString()]", colNames.toString()); + + + reportSQLWithRowNum = reportSQL; + + /* if( endRow != -1) + reportSQL += " WHERE ROWNUM <= " + endRow; + reportSQL += " ) y WHERE rnum >= " + startRow + " ORDER BY rnum"; + return reportSQL;*/ + String parta = Globals.getReportSqlOnlySecondPartA(); + String partb = Globals.getReportSqlOnlySecondPartB(); + + String partSql = ""; + if(!AppUtils.isNotEmpty(getDBType())){ + setDBType(Globals.getDBType()); + } + + int closeBracketPos = 0; + if(wholeSQL_OrderBy.lastIndexOf(")")!= -1) closeBracketPos = wholeSQL_OrderBy.lastIndexOf(")"); + int idxOrderBy = (closeBracketPos>0)?wholeSQL_OrderBy.toUpperCase().indexOf("ORDER BY", closeBracketPos):wholeSQL_OrderBy.toUpperCase().lastIndexOf("ORDER BY"); + String orderbyclause = ""; + if (idxOrderBy < 0) { + orderbyclause = " ORDER BY 1 "; + partSql += " "+ orderbyclause+ " "; + } + else { + orderbyclause = wholeSQL_OrderBy.substring(idxOrderBy); + partSql += " "+ orderbyclause+ " "; + } + + if(getDBType().equals(AppConstants.MYSQL)) { + partSql = partSql+ " LIMIT "+ String.valueOf(startRow)+" , "+ String.valueOf(endRow); + } else if(getDBType().equals(AppConstants.ORACLE)) { + reportSQL = reportSQL.replace(" AS ", " "); + partSql = "where rownum >= "+ String.valueOf(startRow)+" and rownum <= "+(Integer.parseInt(String.valueOf(startRow)) + Integer.parseInt(String.valueOf(endRow))); + } else if(getDBType().equals(AppConstants.POSTGRESQL)) { + partSql = partSql + " LIMIT "+ String.valueOf(endRow)+" , "+ String.valueOf(startRow);//limit [pageSize] offset [startRow] + } + + // Limit only to MYSQL or MariaDB + //if (reportSQL.toUpperCase().indexOf("ORDER BY ") < 0) + //partSql += " ORDER BY 1"; + //else { + + + + /*if(!Globals.isMySQL()) + parta = parta.replace("[endRow]", String.valueOf(endRow)); + else + parta = parta.replace("[startRow]", String.valueOf(startRow)); + + //String partb = Globals.getReportSqlOnlySecondPartB(); + if(!Globals.isMySQL()) + partb = partb.replace("[startRow]", String.valueOf(startRow)); + else + partb = partb.replace("[pageSize]", String.valueOf(getPageSize())); + + if( endRow != -1) + reportSQL += parta;*/ + reportSQL += partSql; + + return reportSQL; + + } // generateSubsetSQL + + public String generateChartSQL(ReportParamValues paramValues, String userId, HttpServletRequest request ) throws RaptorException { + List reportCols = getAllColumns(); + List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns. + String reportSQL = generateSQL(userId, request); + //if(nvl(reportSQL).length()>0) reportSQL = generatedChartSQL; + logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL)); + String legendCol = "1 a"; + // String valueCol = "1"; + StringBuffer groupCol = new StringBuffer(); + StringBuffer seriesCol = new StringBuffer(); + StringBuffer valueCols = new StringBuffer(); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + legendCol = getSelectExpr(dc, colName)+" " + dc.getColId(); + // if(dc.getChartSeq()>0) + // valueCol = "NVL("+colName+", 0) "+dc.getColId(); + if ((!nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + && (dc.getChartSeq()==null || dc.getChartSeq() <= 0) && dc.isGroupBreak()) { + groupCol.append(", "); + groupCol.append(colName + " " + dc.getColId()); + } + } // for + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(dc.isChartSeries()!=null && dc.isChartSeries().booleanValue()) { + //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); + seriesCol.append(", "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))+ " " + dc.getColId()); + } + } + + /*for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(!dc.isChartSeries() && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); + seriesCol.append(", "+ formatChartColumn(getSelectExpr(dc,getColumnSelectStr(dc, paramValues)))+ " " + dc.getColId()); + } + }*/ + + for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); + seriesCol.append("," + formatChartColumn(colName) + " " + dc.getColId()); + } // for + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) + seriesCol.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); + if (colName.equals(AppConstants.RI_CHART_COLOR)) + seriesCol.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR ); + if(colName.equals(AppConstants.RI_CHART_MARKER_START)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_START + " " + AppConstants.RI_CHART_MARKER_START ); + if(colName.equals(AppConstants.RI_CHART_MARKER_END)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_END + " " + AppConstants.RI_CHART_MARKER_END ); + if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_LEFT)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_LEFT + " " + AppConstants.RI_CHART_MARKER_TEXT_LEFT ); + if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_RIGHT)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT + " " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT ); + if(colName.equals(AppConstants.RI_ANOMALY_TEXT)) + seriesCol.append(", " + AppConstants.RI_ANOMALY_TEXT + " " + AppConstants.RI_ANOMALY_TEXT ); + } + + //debugLogger.debug("ReportSQL Chart " + reportSQL ); + /*for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); + valueCols.append("," + formatChartColumn(colName) + " " + dc.getColId()); + } // for + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //if(colName.equals(AppConstants.RI_CHART_TOTAL_COL) || colName.equals(AppConstants.RI_CHART_COLOR)) { + if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) + valueCols.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); + if (colName.equals(AppConstants.RI_CHART_COLOR)) + valueCols.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR ); + if (colName.equals(AppConstants.RI_CHART_INCLUDE)) + valueCols.append(", " + AppConstants.RI_CHART_INCLUDE + " " + AppConstants.RI_CHART_INCLUDE ); + //} + }*/ + String final_sql = ""; + reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM "); + reportSQL = Utils.replaceInString(reportSQL, " select ", " SELECT "); + reportSQL = Utils.replaceInString(reportSQL, " union ", " UNION "); + //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); +// if(reportSQL.indexOf("UNION") != -1) { +// if(reportSQL.indexOf("FROM(")!=-1) +// final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM(") ); +// else if (reportSQL.indexOf("FROM (")!=-1) +// final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM (") ); +// //TODO ELSE THROW ERROR +// } +// else { +// final_sql += " "+reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM ")); +// } + int pos = 0; + int pos_first_select = 0; + int pos_dup_select = 0; + int pos_prev_select = 0; + int pos_last_select = 0; + if (reportSQL.indexOf("FROM", pos)!=-1) { + pos = reportSQL.indexOf("FROM", pos); + pos_dup_select = reportSQL.lastIndexOf("SELECT",pos); + pos_first_select = reportSQL.indexOf("SELECT");//,pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select)); + if(pos_dup_select > pos_first_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select)); + //pos_dup_select1 = pos_dup_select; + pos_prev_select = pos_first_select; + pos_last_select = pos_dup_select; + while (pos_last_select > pos_prev_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select)); + pos = reportSQL.indexOf("FROM", pos+2); + pos_prev_select = pos_last_select; + pos_last_select = reportSQL.lastIndexOf("SELECT",pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select)); + } + } + + } + final_sql += " "+reportSQL.substring(pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("Final SQL " + final_sql)); + String sql = "SELECT " + legendCol + ", " + legendCol+"_1" + seriesCol.toString()+ nvl(valueCols.toString(), ", 1") + + groupCol.toString() + + final_sql; + logger.debug(EELFLoggerDelegate.debugLogger, ("Final sql in generateChartSQL " +sql)); + + return sql; + } // generateChartSQL + + private String formatChartColumn(String colName) { + + logger.debug(EELFLoggerDelegate.debugLogger, ("Format Chart Column Input colName" + colName)); + colName = colName.trim(); + colName = Utils.replaceInString(colName, "TO_CHAR", "to_char"); + colName = Utils.replaceInString(colName, "to_number", "TO_NUMBER"); + //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); + colName = colName.replaceAll(",[\\s]*\\(", ",("); + StringBuffer colNameBuf = new StringBuffer(colName); + int pos = 0, posFormatStart = 0, posFormatEnd = 0; + String format = ""; + if(colNameBuf.indexOf("999")==-1 && colNameBuf.indexOf("990")==-1) { + logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); + return colNameBuf.toString(); + } + while (colNameBuf.indexOf("to_char")!=-1) { + if(colNameBuf.indexOf("999")!=-1 || colNameBuf.indexOf("990")!=-1) { + pos = colNameBuf.indexOf("to_char"); + colNameBuf.insert(pos, " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ("); + pos = colNameBuf.indexOf("to_char"); + colNameBuf.replace(pos, pos+7, "TO_CHAR"); + //colName = Utils.replaceInString(colNameBuf.toString(), "to_char", " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ( TO_CHAR "); + logger.debug(EELFLoggerDelegate.debugLogger, ("After adding to_number " + colNameBuf.toString())); + //posFormatStart = colNameBuf.lastIndexOf(",'")+1; + posFormatStart = colNameBuf.indexOf(",'", pos)+1; + posFormatEnd = colNameBuf.indexOf(")",posFormatStart); + logger.debug(EELFLoggerDelegate.debugLogger, (posFormatStart + " " + posFormatEnd + " "+ pos)); + format = colNameBuf.substring(posFormatStart, posFormatEnd); + //posFormatEnd = colNameBuf.indexOf(")",posFormatEnd); + colNameBuf.insert(posFormatEnd+1, " ," + format + ") , "+ format + ")"); + logger.debug(EELFLoggerDelegate.debugLogger, ("colNameBuf " + colNameBuf.toString())); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); + return colNameBuf.toString(); + } + public String generateTotalSQLLinear(ReportParamValues paramValues, String userId, HttpServletRequest request) throws RaptorException { + List reportCols = getAllColumns(); + String reportSQL = generateSQL(userId,request); + //debugLogger.debug("After GenerateSQL " + reportSQL); + + StringBuffer sbSelect = new StringBuffer(); + StringBuffer sbTotal = new StringBuffer(); + StringBuffer colNames = new StringBuffer(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + + DataColumnType dc = (DataColumnType) iter.next(); + if (colNames.length() > 0) + colNames.append(", "); + colNames.append(dc.getColId()); + } + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + //if (!dct.isVisible()) + // continue; + + String colName = getColumnSelectStr(dct, paramValues); + + sbSelect.append((sbSelect.length() == 0) ? "SELECT " : ", "); + + sbSelect.append(colName); + sbSelect.append(" "); + sbSelect.append(dct.getColId()); + + + sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", "); + if (nvl(dct.getDisplayTotal()).length() > 0) { + // sbTotal.append(getSelectExpr(dct, + // dct.getDisplayTotal()+dct.getColId()+")")); + String displayTotal = dct.getDisplayTotal(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < displayTotal.length(); i++) { + char ch = displayTotal.charAt(i); + if (ch == '+' || ch == '-') + sb.append(dct.getColId() + ")"); + sb.append(ch); + } // for + sb.append(dct.getColId() + ")"); + + //debugLogger.debug("SB " + sb.toString() + "\n " + getSelectExpr(dct, sb.toString())); + sbTotal.append(getSelectExpr(dct, sb.toString())); + //debugLogger.debug("SBTOTAL " + sbTotal.toString()); + } else + sbTotal.append("NULL"); + sbTotal.append(" total_"); + sbTotal.append(dct.getColId()); + } // for + + //debugLogger.debug(" ****** " + sbTotal.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, ("REPORTWRAPPER " + reportSQL)); + int pos = 0; + int pos_first_select = 0; + int pos_dup_select = 0; + int pos_prev_select = 0; + int pos_last_select = 0; + + //reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM "); + //reportSQL = Utils.replaceInString(reportSQL, "select ", "SELECT "); + reportSQL = replaceNewLine(reportSQL, " from ", " FROM "); + reportSQL = replaceNewLine(reportSQL, "from ", " FROM "); + reportSQL = replaceNewLine(reportSQL, "FROM ", " FROM "); + + reportSQL = " "+reportSQL; + reportSQL = replaceNewLine(reportSQL, "select ", " SELECT "); + reportSQL = replaceNewLine(reportSQL, "SELECT ", " SELECT "); + if (reportSQL.indexOf("FROM", pos)!=-1) { + pos = reportSQL.indexOf("FROM", pos); + pos_dup_select = reportSQL.lastIndexOf("SELECT",pos); + pos_first_select = reportSQL.indexOf("SELECT");//,pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select)); + if(pos_dup_select > pos_first_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select)); + //pos_dup_select1 = pos_dup_select; + pos_prev_select = pos_first_select; + pos_last_select = pos_dup_select; + while (pos_last_select > pos_prev_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select)); + pos = reportSQL.indexOf("FROM", pos+2); + pos_prev_select = pos_last_select; + pos_last_select = reportSQL.lastIndexOf("SELECT",pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select)); + } + } + + } + + + //sbSelect.append(reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM "))); + + logger.debug(EELFLoggerDelegate.debugLogger, (" *************** " + pos + " " + reportSQL)); + //sbSelect.append(" "+ reportSQL.substring(pos)); + sbSelect.append(" "+reportSQL.substring(pos)); + logger.debug(EELFLoggerDelegate.debugLogger, (" **************** " + sbSelect.toString())); + sbTotal.append(" FROM ("); + sbTotal.append(sbSelect.toString()); + sbTotal.append(") totalSQL"); + + String dbType = ""; + String dbInfo = getDBInfo(); + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + if (dbType.equals("DAYTONA")) { + sbTotal.append("("+ colNames+ ")"); + } + String sql = sbTotal.toString(); + sql = Utils.replaceInString(sql, " from ", " FROM "); + sql = Utils.replaceInString(sql, "select ", "SELECT "); + //sql = Utils.replaceInString(sql, " select ", " SELECT "); + logger.debug(EELFLoggerDelegate.debugLogger, ("Before SQL Corrector " + sql)); + String corrected_SQL = new SQLCorrector().fixSQL(new StringBuffer(sql)); + logger.debug(EELFLoggerDelegate.debugLogger, ("************")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Corrected SQL " + corrected_SQL)); + return corrected_SQL; + //return sbTotal.toString(); + } // generateTotalSQLLinear + + public String generateTotalSQLCrossTab(String sql, String rowColPos, + String userId, HttpServletRequest request, ReportParamValues paramValues) throws RaptorException { + List reportCols = getAllColumns(); + String reportSQL = sql; + + StringBuffer sbSelect = new StringBuffer(); + StringBuffer sbGroup = new StringBuffer(); + // StringBuffer sbOrder = new StringBuffer(); + StringBuffer sbTotal = new StringBuffer(); + StringBuffer colNames = new StringBuffer(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + + DataColumnType dc = (DataColumnType) iter.next(); + if (colNames.length() > 0) + colNames.append(", "); + colNames.append(dc.getColId()); + } + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (!dct.isVisible()) + continue; + + + String colName = getColumnSelectStr(dct, paramValues); + String colExpr = getSelectExpr(dct, colName); + + sbSelect.append((sbSelect.length() == 0) ? "SELECT " : ", "); + + if (nvl(dct.getCrossTabValue()).equals(rowColPos)) { + //sbSelect.append(colExpr); + sbSelect.append(dct.getColId()); + sbGroup.append((sbGroup.length() == 0) ? " GROUP BY " : ", "); + sbGroup.append(dct.getColId()); + + /* + * sbOrder.append((sbOrder.length()==0)?" ORDER BY ":", "); + * sbOrder.append(dct.getColId()); + * if(dct.getColType().equals(AppConstants.CT_DATE)) + * sbOrder.append(" DESC"); + */ + + sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", "); + sbTotal.append(dct.getColId()); + } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) { + //sbSelect.append(colName); + sbSelect.append(dct.getColId()); + + String displayTotal = getCrossTabDisplayTotal(rowColPos); + if (displayTotal.length() > 0) { + // displayTotal += dct.getColId()+")"; + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < displayTotal.length(); i++) { + char ch = displayTotal.charAt(i); + if (ch == '+' || ch == '-') + sb.append(dct.getColId() + ")"); + sb.append(ch); + } // for + sb.append(dct.getColId() + ")"); + + displayTotal = sb.toString(); + } else + displayTotal = "COUNT(*)"; + + sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", "); + sbTotal.append(getSelectExpr(dct, displayTotal)); + sbTotal.append(" total_"); + sbTotal.append(dct.getColId()); + } else { + //sbSelect.append(colExpr); + sbSelect.append(dct.getColId()); + } // if + + sbSelect.append(" "); + sbSelect.append(dct.getColId()); + } // for + + sbSelect.append(reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM "))); + + sbTotal.append(" FROM ("); + sbTotal.append(sbSelect.toString()); + sbTotal.append(") totalSQL"); + sbTotal.append(sbGroup.toString()); + String dbType = ""; + String dbInfo = getDBInfo(); + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + if (dbType.equals("DAYTONA")) { + sbTotal.append("("+ colNames+ ")"); + } + + // sbTotal.append(sbOrder.toString()); + + //debugLogger.debug(getReportDefType() + " " + AppConstants.RD_SQL_BASED); + //debugLogger.debug("SQL To Delete " + sbTotal.toString()); + sql = ""; + if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) { + sql = Utils.replaceInString(sbTotal.toString(), " from ", " FROM "); + sql = Utils.replaceInString(sql, "select ", "SELECT "); + return new SQLCorrector().fixSQL(new StringBuffer(sql)); + } + + return sbTotal.toString(); + + } // generateTotalSQLCrossTab + + + public String generateTotalSQLCrossTab(ReportParamValues paramValues, String rowColPos, + String userId, HttpServletRequest request) throws RaptorException { + List reportCols = getAllColumns(); + String reportSQL = generateSQL(userId, request); + + StringBuffer sbSelect = new StringBuffer(); + StringBuffer sbGroup = new StringBuffer(); + // StringBuffer sbOrder = new StringBuffer(); + StringBuffer sbTotal = new StringBuffer(); + StringBuffer colNames = new StringBuffer(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + + DataColumnType dc = (DataColumnType) iter.next(); + if (colNames.length() > 0) + colNames.append(", "); + colNames.append(dc.getColId()); + } + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (!dct.isVisible()) + continue; + + String colName = getColumnSelectStr(dct, paramValues); + String colExpr = getSelectExpr(dct, colName); + + sbSelect.append((sbSelect.length() == 0) ? "SELECT " : ", "); + + if (nvl(dct.getCrossTabValue()).equals(rowColPos)) { + sbSelect.append(colExpr); + + sbGroup.append((sbGroup.length() == 0) ? " GROUP BY " : ", "); + sbGroup.append(dct.getColId()); + + /* + * sbOrder.append((sbOrder.length()==0)?" ORDER BY ":", "); + * sbOrder.append(dct.getColId()); + * if(dct.getColType().equals(AppConstants.CT_DATE)) + * sbOrder.append(" DESC"); + */ + + sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", "); + sbTotal.append(dct.getColId()); + } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) { + sbSelect.append(colName); + + String displayTotal = getCrossTabDisplayTotal(rowColPos); + if (displayTotal.length() > 0) { + // displayTotal += dct.getColId()+")"; + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < displayTotal.length(); i++) { + char ch = displayTotal.charAt(i); + if (ch == '+' || ch == '-') + sb.append(dct.getColId() + ")"); + sb.append(ch); + } // for + sb.append(dct.getColId() + ")"); + + displayTotal = sb.toString(); + } else + displayTotal = "COUNT(*)"; + + sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", "); + sbTotal.append(getSelectExpr(dct, displayTotal)); + sbTotal.append(" total_"); + sbTotal.append(dct.getColId()); + } else { + sbSelect.append(colExpr); + } // if + + sbSelect.append(" "); + sbSelect.append(dct.getColId()); + } // for + + sbSelect.append(reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM "))); + + sbTotal.append(" FROM ("); + sbTotal.append(sbSelect.toString()); + sbTotal.append(") totalSQL"); + sbTotal.append(sbGroup.toString()); + String dbType = ""; + String dbInfo = getDBInfo(); + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + if (dbType.equals("DAYTONA")) { + sbTotal.append("("+ colNames+ ")"); + } + + // sbTotal.append(sbOrder.toString()); + + //debugLogger.debug(getReportDefType() + " " + AppConstants.RD_SQL_BASED); + //debugLogger.debug("SQL To Delete " + sbTotal.toString()); + String sql = ""; + if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) { + sql = Utils.replaceInString(sbTotal.toString(), " from ", " FROM "); + sql = Utils.replaceInString(sql, "select ", "SELECT "); + return new SQLCorrector().fixSQL(new StringBuffer(sql)); + } + + return sbTotal.toString(); + + } // generateTotalSQLCrossTab + + public String generateDistinctValuesSQL(ReportParamValues paramValues, DataColumnType dct, + String userId, HttpServletRequest request) throws RaptorException { + DataSourceType dst = getColumnTableById(dct.getColId()); + String colName = getColumnSelectStr(dct, paramValues); + String colExpr = getSelectExpr(dct, colName); + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + StringBuffer sb = new StringBuffer(); + sb.append("SELECT DISTINCT "); + if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) { + sb.append(dct.getColId()); + sb.append(" FROM ("); + //paramvalues added below to filter distinct values based on formfields. + //sb.append(generateSQL(paramValues, userId, request)); + sb.append(rr.getWholeSQL()); + sb.append(") " + (Globals.isPostgreSQL() || Globals.isMySQL() ?" AS ":"") + " report_sql ORDER BY 1"); + } else { + sb.append(colExpr); + sb.append(" "); + sb.append(dct.getColId()); + if (!colExpr.equals(colName)) { + sb.append(", "); + sb.append(colName); + } // if + sb.append(" FROM "); + sb.append(dst.getTableName()); + sb.append(" "); + sb.append(dst.getTableId()); + sb.append(" ORDER BY "); + sb.append(colName); + if (dct.getColType().equals(AppConstants.CT_DATE)) + sb.append(" DESC"); + } // else + + return sb.toString(); + } // generateDistinctValuesSQL + + /** ************************************************************************************************* */ + + public DataSourceType getTableWithoutColumns() { + List dsList = getDataSourceList().getDataSource(); + for (Iterator iter = dsList.iterator(); iter.hasNext();) { + DataSourceType ds = (DataSourceType) iter.next(); + + if (ds.getDataColumnList().getDataColumn().size() == 0) + return ds; + } // for + + return null; + } // getTableWithoutColumns + + public CustomReportType cloneCustomReportClearTables() throws RaptorException { + ReportWrapper nrw = new ReportWrapper(cloneCustomReport(), reportID, getOwnerID(), + getCreateID(), getCreateDate(), getUpdateID(), getUpdateDate(), getMenuID(), + isMenuApproved()); + + DataSourceType ndst = null; + while ((ndst = nrw.getTableWithoutColumns()) != null) + nrw.deleteDataSourceType(ndst.getTableId()); + + return nrw.getCustomReport(); + } // cloneCustomReportClearTables + + public String marshal() throws RaptorException { + StringWriter sw = new StringWriter(); + ObjectFactory objFactory = new ObjectFactory(); + + try { + JAXBContext jc = JAXBContext.newInstance("org.openecomp.portalsdk.analytics.xmlobj"); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + //JAXBElement jaxbElement = new JAXBElement(new QName("customReport"), Object.class, ""); + //m.marshal( System.out ); + //m.marshal(jaxbElement, new StreamResult(sw)); + m.marshal((getTableWithoutColumns() == null) ? objFactory.createCustomReport(cr) : objFactory.createCustomReport(cloneCustomReportClearTables()), + new StreamResult(sw)); + } catch (JAXBException ex) { + throw new RaptorException (ex.getMessage(), ex.getCause()); + } + return sw.toString(); + } // marshal + + public static CustomReportType unmarshalCR(String reportXML) throws RaptorException { + //CustomReport cr = null; + try { + JAXBContext jc = JAXBContext.newInstance("org.openecomp.portalsdk.analytics.xmlobj"); + Unmarshaller u = jc.createUnmarshaller(); + javax.xml.bind.JAXBElement doc = (javax.xml.bind.JAXBElement) u.unmarshal(new java.io.StringReader( + reportXML)); + return doc.getValue(); + } catch (JAXBException ex) { + ex.printStackTrace(); + throw new RaptorException (ex.getMessage(), ex.getCause()); + } + + + } // unmarshal + + protected static CustomReportType createBlankCR() throws RaptorException { + return createBlankCR("N/A"); + } // createBlank + + protected static CustomReportType createBlankCR(String createID) throws RaptorException { + ObjectFactory objFactory = new ObjectFactory(); + CustomReportType cr = objFactory.createCustomReportType(); + //CustomReport cr = null; + try { + //cr = (CustomReport) objFactory.createCustomReport(customReportType); + + cr.setReportName(""); + cr.setReportDescr(""); + cr.setChartType(""); + cr.setPublic(false); + cr.setCreateId(createID); + cr.setCreateDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar())); + // cr.setReportSQL(""); + cr.setReportType(""); + cr.setPageSize(50); + + DataSourceList dataSourceList = objFactory.createDataSourceList(); + cr.setDataSourceList(dataSourceList); + } catch (DatatypeConfigurationException ex) { + throw new RaptorException (ex.getMessage(), ex.getCause()); + } + return cr; + } // createBlank + + protected void replaceCustomReportWithClone() throws RaptorException { + try { + CustomReportType clone = cloneCustomReport(); + this.cr = clone; + } catch (Exception e) { + e.printStackTrace(); + logger.debug(EELFLoggerDelegate.debugLogger, ("[SYSTEM ERROR] ReportWrapper.replaceCustomReportWithClone generated exception for report [" + + reportID + "]. Exception: " + e.getMessage())); + throw new RaptorException("[SYSTEM ERROR] ReportWrapper.replaceCustomReportWithClone generated exception for report [" + + reportID + "]. Exception: " + e.getMessage(), e.getCause()); + } + } // replaceCustomReportWithClone + + /** ************************************************************************************************* */ + + public FormatType cloneFormatType(ObjectFactory objFactory, FormatType ft) + throws JAXBException { + FormatType nft = objFactory.createFormatType(); + + nft.setLessThanValue(ft.getLessThanValue()); + nft.setExpression(ft.getExpression()); + nft.setBold(ft.isBold()); + nft.setItalic(ft.isItalic()); + nft.setUnderline(ft.isUnderline()); + if (nvl(ft.getBgColor()).length() > 0) + nft.setBgColor(ft.getBgColor()); + if (nvl(ft.getFontColor()).length() > 0) + nft.setFontColor(ft.getFontColor()); + if (nvl(ft.getFontFace()).length() > 0) + nft.setFontFace(ft.getFontFace()); + if (nvl(ft.getFontSize()).length() > 0) + nft.setFontSize(ft.getFontSize()); + if (nvl(ft.getAlignment()).length() > 0) + nft.setAlignment(ft.getAlignment()); + if (nvl(ft.getComment()).length() > 0) + nft.setComment(ft.getComment()); + + nft.setFormatId(ft.getFormatId()); + + return nft; + } // cloneFormatType + + public SemaphoreType cloneSemaphoreType(ObjectFactory objFactory, SemaphoreType st) + throws JAXBException { + SemaphoreType nst = objFactory.createSemaphoreType(); + + nst.setSemaphoreName(st.getSemaphoreName()); + nst.setSemaphoreType(st.getSemaphoreType()); + nst.setSemaphoreId(st.getSemaphoreId()); + if (nvl(st.getComment()).length() > 0) + nst.setComment(st.getComment()); + + if (st.getFormatList() != null) { + FormatList formatList = objFactory.createFormatList(); + nst.setFormatList(formatList); + + for (Iterator iter = st.getFormatList().getFormat().iterator(); iter.hasNext();) + formatList.getFormat().add( + cloneFormatType(objFactory, (FormatType) iter.next())); + } // if + + return nst; + } // cloneSemaphoreType + + public Reports cloneDashboardType(ObjectFactory objFactory, Reports rpt) + throws JAXBException { + Reports nrpt = objFactory.createReports(); + + nrpt.setReportId(rpt.getReportId()); + nrpt.setBgcolor(rpt.getBgcolor()); + return nrpt; + } // cloneDashboardType + + public Marker cloneMarkerType(ObjectFactory objFactory, Marker marker) + throws JAXBException { + Marker nMarker = objFactory.createMarker(); + nMarker.setAddressColumn(marker.getAddressColumn()); + nMarker.setDataColumn(marker.getDataColumn()); + nMarker.setDataHeader(marker.getDataHeader()); + nMarker.setMarkerColor(marker.getMarkerColor()); + return nMarker; + } // cloneDashboardType + + public ChartDrillFormfield cloneChartDrillFormfield(ObjectFactory objFactory, ChartDrillFormfield chartDrillFormfield) + throws JAXBException { + ChartDrillFormfield nChartDrillFormfield = objFactory.createChartDrillFormfield(); + nChartDrillFormfield.setFormfield(chartDrillFormfield.getFormfield()); + return nChartDrillFormfield; + } // cloneDashboardType + + public boolean isChartDrillDownContainsName(String name) { + for (Iterator iter = getChartDrillOptions().getTargetFormfield().iterator(); iter + .hasNext();) { + org.openecomp.portalsdk.analytics.xmlobj.ChartDrillFormfield cdf = (org.openecomp.portalsdk.analytics.xmlobj.ChartDrillFormfield) iter.next(); + if(cdf.getFormfield().equals(name)) { + return true; + } + } + return false; + } + public FormFieldType cloneFormFieldType(ObjectFactory objFactory, FormFieldType fft) + throws JAXBException { + FormFieldType nfft = objFactory.createFormFieldType(); + + nfft.setColId(fft.getColId()); + nfft.setFieldName(fft.getFieldName()); + nfft.setFieldType(fft.getFieldType()); + if (nvl(fft.getVisible()).length() > 0) + nfft.setVisible(fft.getVisible()); + if (nvl(fft.getValidationType()).length() > 0) + nfft.setValidationType(fft.getValidationType()); + if (nvl(fft.getMandatory()).length() > 0) + nfft.setMandatory(fft.getMandatory()); + if (nvl(fft.getDefaultValue()).length() > 0) + nfft.setDefaultValue(fft.getDefaultValue()); + nfft.setOrderBySeq(fft.getOrderBySeq()); + if (nvl(fft.getFieldSQL()).length() > 0) + nfft.setFieldSQL(fft.getFieldSQL()); + if (nvl(fft.getFieldDefaultSQL()).length() > 0) + nfft.setFieldDefaultSQL(fft.getFieldDefaultSQL()); + if(fft.getRangeStartDate()!=null) + nfft.setRangeStartDate(fft.getRangeStartDate()); + if(fft.getRangeEndDate()!=null) + nfft.setRangeEndDate(fft.getRangeEndDate()); + if(fft.getRangeStartDateSQL()!=null) + nfft.setRangeStartDateSQL(fft.getRangeStartDateSQL()); + if(fft.getRangeEndDateSQL()!=null) + nfft.setRangeEndDateSQL(fft.getRangeEndDateSQL()); + + if (nvl(fft.getComment()).length() > 0) + nfft.setComment(fft.getComment()); + + if (fft.getPredefinedValueList() != null) { + PredefinedValueList predefinedValueList = objFactory.createPredefinedValueList(); + nfft.setPredefinedValueList(predefinedValueList); + + for (Iterator iter = fft.getPredefinedValueList().getPredefinedValue().iterator(); iter + .hasNext();) + predefinedValueList.getPredefinedValue().add(new String((String) iter.next())); + } // if + if (nvl(fft.getDependsOn()).length() > 0) + nfft.setDependsOn(fft.getDependsOn()); + + nfft.setGroupFormField((fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue())?true:false); + if (nvl(fft.getMultiSelectListSize()).length() > 0) + nfft.setMultiSelectListSize(fft.getMultiSelectListSize()); + + nfft.setFieldId(fft.getFieldId()); + return nfft; + } // cloneFormFieldType + + public JavascriptItemType cloneJavascriptType(ObjectFactory objFactory, JavascriptItemType jit) + throws JAXBException { + JavascriptItemType njit = objFactory.createJavascriptItemType(); + + njit.setId(jit.getId()); + njit.setFieldId(jit.getFieldId()); + njit.setCallText(jit.getCallText()); + return njit; + } // cloneJavascriptType + + public ColFilterType cloneColFilterType(ObjectFactory objFactory, ColFilterType cft) + throws JAXBException { + ColFilterType ncft = objFactory.createColFilterType(); + + ncft.setColId(cft.getColId()); + ncft.setFilterSeq(cft.getFilterSeq()); + ncft.setJoinCondition(cft.getJoinCondition()); + if (nvl(cft.getOpenBrackets()).length() > 0) + ncft.setOpenBrackets(cft.getOpenBrackets()); + ncft.setExpression(cft.getExpression()); + if (nvl(cft.getArgType()).length() > 0) + ncft.setArgType(cft.getArgType()); + if (nvl(cft.getArgValue()).length() > 0) + ncft.setArgValue(cft.getArgValue()); + if (nvl(cft.getCloseBrackets()).length() > 0) + ncft.setCloseBrackets(cft.getCloseBrackets()); + if (nvl(cft.getComment()).length() > 0) + ncft.setComment(cft.getComment()); + + return ncft; + } // cloneColFilterType + + public DataColumnType cloneDataColumnType(ObjectFactory objFactory, DataColumnType dct) + throws JAXBException { + DataColumnType ndct = objFactory.createDataColumnType(); + + ndct.setTableId(dct.getTableId()); + ndct.setDbColName(dct.getDbColName()); + if (nvl(dct.getCrossTabValue()).length() > 0) + ndct.setCrossTabValue(dct.getCrossTabValue()); + ndct.setColName(dct.getColName()); + ndct.setDisplayName(dct.getDisplayName()); + if (dct.getDisplayWidth() > 0) + ndct.setDisplayWidth(dct.getDisplayWidth()); + if (nvl(dct.getDisplayWidthInPxls()).length()>0) + ndct.setDisplayWidthInPxls(dct.getDisplayWidthInPxls()); + if (nvl(dct.getDisplayAlignment()).length() > 0) + ndct.setDisplayAlignment(dct.getDisplayAlignment()); + if (nvl(dct.getDisplayHeaderAlignment()).length() > 0) + ndct.setDisplayHeaderAlignment(dct.getDisplayHeaderAlignment()); + ndct.setOrderSeq(dct.getOrderSeq()); + ndct.setVisible(dct.isVisible()); + ndct.setCalculated(dct.isCalculated()); + ndct.setColType(dct.getColType()); + if(dct.getColType().equals(AppConstants.CT_HYPERLINK)) { + ndct.setHyperlinkURL(dct.getHyperlinkURL()); + ndct.setHyperlinkType(dct.getHyperlinkType()); + if(dct.getHyperlinkType().equals("IMAGE")) { + ndct.setActionImg(dct.getActionImg()); + } + } + + if(dct.getIndentation()!=null) { + ndct.setIndentation(dct.getIndentation()); + } + + if (nvl(dct.getColFormat()).length() > 0) + ndct.setColFormat(dct.getColFormat()); + ndct.setGroupBreak(dct.isGroupBreak()); + ndct.setNowrap(dct.getNowrap()); + if (nvl(dct.getYAxis()).length() > 0) + ndct.setYAxis(dct.getYAxis()); + if (dct.getOrderBySeq()!=null && dct.getOrderBySeq() > 0) + ndct.setOrderBySeq(dct.getOrderBySeq()); + if (nvl(dct.getOrderByAscDesc()).length() > 0) + ndct.setOrderByAscDesc(dct.getOrderByAscDesc()); + if (nvl(dct.getDisplayTotal()).length() > 0) + ndct.setDisplayTotal(dct.getDisplayTotal()); + if (nvl(dct.getColOnChart()).length() > 0) + ndct.setColOnChart(dct.getColOnChart()); + if (dct.getChartSeq() !=null) + ndct.setChartSeq(dct.getChartSeq()); + if (nvl(dct.getChartColor()).length() > 0) + ndct.setChartColor(dct.getChartColor()); + if (nvl(dct.getChartLineType()).length() > 0) + ndct.setChartLineType(dct.getChartLineType()); + ndct.setChartSeries((dct.isChartSeries()!=null && dct.isChartSeries().booleanValue())?true:false); + ndct.setIsRangeAxisFilled((dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue())?true:false); + + if (dct.isCreateInNewChart()!=null) + ndct.setCreateInNewChart(dct.isCreateInNewChart()); + if (nvl(dct.getDrillDownType()).length() > 0) + ndct.setDrillDownType(dct.getDrillDownType()); + ndct.setDrillinPoPUp(dct.isDrillinPoPUp()!=null?dct.isDrillinPoPUp():false); + if (nvl(dct.getDrillDownURL()).length() > 0) + ndct.setDrillDownURL(dct.getDrillDownURL()); + if (nvl(dct.getDrillDownParams()).length() > 0) + ndct.setDrillDownParams(dct.getDrillDownParams()); + if (nvl(dct.getComment()).length() > 0) + ndct.setComment(dct.getComment()); + if (nvl(dct.getDependsOnFormField()).length() > 0) + ndct.setDependsOnFormField(dct.getDependsOnFormField()); + if (dct.getColFilterList() != null) { + ColFilterList colFilterList = objFactory.createColFilterList(); + ndct.setColFilterList(colFilterList); + + for (Iterator iter = dct.getColFilterList().getColFilter().iterator(); iter + .hasNext();) + colFilterList.getColFilter().add( + cloneColFilterType(objFactory, (ColFilterType) iter.next())); + } // if + + if (nvl(dct.getSemaphoreId()).length() > 0) + ndct.setSemaphoreId(dct.getSemaphoreId()); + if (nvl(dct.getDbColType()).length() > 0) + ndct.setDbColType(dct.getDbColType()); + else { + ndct.setDbColType(dct.getColType()); + adjustColumnType(ndct); + } + if (nvl(dct.getChartGroup()).length() > 0) + ndct.setChartGroup(dct.getChartGroup()); + + if (nvl(dct.getYAxis()).length() > 0) + ndct.setYAxis(dct.getYAxis()); + + if (nvl(dct.getDependsOnFormField()).length() > 0) + ndct.setDependsOnFormField(dct.getDependsOnFormField()); + + + + if(nvl(dct.getNowrap()).length() > 0) + ndct.setNowrap(dct.getNowrap()); + + if(dct.getIndentation()!=null) { + ndct.setIndentation(dct.getIndentation()); + } + + ndct.setEnhancedPagination((dct.isEnhancedPagination()!=null && dct.isEnhancedPagination().booleanValue())?true:false); + if(nvl(dct.getDataMiningCol()).length() > 0) + ndct.setDataMiningCol(dct.getDataMiningCol()); + + ndct.setColId(dct.getColId()); + + // ndct.setSemaphoreId(nvl(dct.getSemaphoreId())); + // if(nvl(dct.getDbColType()).length()>0) + // ndct.setDbColType(dct.getDbColType()); + return ndct; + } // cloneDataColumnType + + public DataSourceType cloneDataSourceType(ObjectFactory objFactory, DataSourceType dst) + throws JAXBException { + DataSourceType ndst = objFactory.createDataSourceType(); + + ndst.setTableName(dst.getTableName()); + ndst.setTablePK(dst.getTablePK()); + ndst.setDisplayName(dst.getDisplayName()); + if (nvl(dst.getRefTableId()).length() > 0) + ndst.setRefTableId(dst.getRefTableId()); + if (nvl(dst.getRefDefinition()).length() > 0) + ndst.setRefDefinition(dst.getRefDefinition()); + if (nvl(dst.getComment()).length() > 0) + ndst.setComment(dst.getComment()); + DataColumnList dataColumnList = objFactory.createDataColumnList(); + ndst.setDataColumnList(dataColumnList); + + for (Iterator iter = dst.getDataColumnList().getDataColumn().iterator(); iter + .hasNext();) + dataColumnList.getDataColumn().add( + cloneDataColumnType(objFactory, (DataColumnType) iter.next())); + ndst.setTableId(dst.getTableId()); + + + return ndst; + } // cloneDataSourceType + + public CustomReportType cloneCustomReport() throws RaptorException { + ObjectFactory objFactory = new ObjectFactory(); + CustomReportType ncr = objFactory.createCustomReportType(); + + //CustomReport ncr = null; + try { + //ncr = (CustomReport) objFactory.createCustomReport(customReportType); + ncr.setReportName(cr.getReportName()); + ncr.setReportDescr(cr.getReportDescr()); + if (nvl(cr.getNumDashCols()).length() > 0) + ncr.setNumDashCols(cr.getNumDashCols()); + if (nvl(cr.getDashboardLayoutHTML()).length() > 0) + ncr.setDashboardLayoutHTML(cr.getDashboardLayoutHTML()); + if (nvl(cr.getDbInfo()).length() > 0) + ncr.setDbInfo(cr.getDbInfo()); + ncr.setChartType(cr.getChartType()); + if (nvl(cr.getChartTypeFixed()).length() > 0) + ncr.setChartTypeFixed(cr.getChartTypeFixed()); + if (nvl(cr.getChartMultiSeries()).length() > 0) + ncr.setChartMultiSeries(cr.getChartMultiSeries()); + if (nvl(cr.getChartLeftAxisLabel()).length() > 0) + ncr.setChartLeftAxisLabel(cr.getChartLeftAxisLabel()); + if (nvl(cr.getChartRightAxisLabel()).length() > 0) + ncr.setChartRightAxisLabel(cr.getChartRightAxisLabel()); + if (nvl(cr.getChartWidth()).length() > 0) + ncr.setChartWidth(cr.getChartWidth()); + if (nvl(cr.getChartHeight()).length() > 0) + ncr.setChartHeight(cr.getChartHeight()); + ncr.setShowChartTitle(cr.isShowChartTitle()); + ncr.setPublic(cr.isPublic()); + ncr.setHideFormFieldAfterRun(cr.isHideFormFieldAfterRun()); + ncr.setCreateId(cr.getCreateId()); + ncr.setCreateDate(cr.getCreateDate()); + if (nvl(cr.getReportSQL()).length() > 0) + ncr.setReportSQL(cr.getReportSQL()); + if (nvl(cr.getReportTitle()).length() > 0) + ncr.setReportTitle(cr.getReportTitle()); + if (nvl(cr.getReportSubTitle()).length() > 0) + ncr.setReportSubTitle(cr.getReportSubTitle()); + if (nvl(cr.getReportHeader()).length() > 0) + ncr.setReportHeader(cr.getReportHeader()); + if (cr.getFrozenColumns()!=null) + ncr.setFrozenColumns(cr.getFrozenColumns()); + if (nvl(cr.getPdfImgLogo()).length()>0) + ncr.setPdfImgLogo(cr.getPdfImgLogo()); + if (nvl(cr.getEmptyMessage()).length()>0) + ncr.setEmptyMessage(cr.getEmptyMessage()); + if (nvl(cr.getWidthNoColumn()).length()>0) + ncr.setWidthNoColumn(cr.getWidthNoColumn()); + if (nvl(cr.getDataGridAlign()).length()>0) + ncr.setDataGridAlign(cr.getDataGridAlign()); + + if (nvl(cr.getReportFooter()).length() > 0) + ncr.setReportFooter(cr.getReportFooter()); + if (nvl(cr.getNumFormCols()).length() > 0) + ncr.setNumFormCols(cr.getNumFormCols()); + if (nvl(cr.getDisplayOptions()).length() > 0) + ncr.setDisplayOptions(cr.getDisplayOptions()); + if (nvl(cr.getDataContainerHeight()).length() > 0) + ncr.setDataContainerHeight(cr.getDataContainerHeight()); + if (nvl(cr.getDataContainerWidth()).length() > 0) + ncr.setDataContainerWidth(cr.getDataContainerWidth()); + if (nvl(cr.getAllowSchedule()).length() > 0) + ncr.setAllowSchedule(cr.getAllowSchedule()); + if (nvl(cr.getTopDown()).length() > 0) + ncr.setTopDown(cr.getTopDown()); + if (nvl(cr.getSizedByContent()).length() > 0) + ncr.setSizedByContent(cr.getSizedByContent()); + if (nvl(cr.getComment()).length() > 0) + ncr.setComment(cr.getComment()); + if (nvl(cr.getDashboardOptions()).length()>0) + ncr.setDashboardOptions(cr.getDashboardOptions()); + + if(cr.isDashboardType()!=null) + ncr.setDashboardType(cr.isDashboardType()); + if(cr.isReportInNewWindow()!=null) + ncr.setReportInNewWindow(cr.isReportInNewWindow()); + ncr.setDisplayFolderTree(cr.isDisplayFolderTree()); + if (cr.getDashBoardReports() == null) { + if (cr.getMaxRowsInExcelDownload()!=null && cr.getMaxRowsInExcelDownload()>0) + ncr.setMaxRowsInExcelDownload(cr.getMaxRowsInExcelDownload()); + } + + if (nvl(cr.getJavascriptElement()).length()>0) + ncr.setJavascriptElement(cr.getJavascriptElement()); + if (nvl(cr.getFolderId()).length()>0) + ncr.setFolderId(cr.getFolderId()); + ncr.setDrillURLInPoPUpPresent((cr.isDrillURLInPoPUpPresent()!=null && cr.isDrillURLInPoPUpPresent().booleanValue())?true:false); + + if (nvl(cr.getIsOneTimeScheduleAllowed()).length()>0) + ncr.setIsOneTimeScheduleAllowed(cr.getIsOneTimeScheduleAllowed()); + if (nvl(cr.getIsHourlyScheduleAllowed()).length()>0) + ncr.setIsHourlyScheduleAllowed(cr.getIsHourlyScheduleAllowed()); + if (nvl(cr.getIsDailyScheduleAllowed()).length()>0) + ncr.setIsDailyScheduleAllowed(cr.getIsDailyScheduleAllowed()); + if (nvl(cr.getIsDailyMFScheduleAllowed()).length()>0) + ncr.setIsDailyMFScheduleAllowed(cr.getIsDailyMFScheduleAllowed()); + if (nvl(cr.getIsWeeklyScheduleAllowed()).length()>0) + ncr.setIsWeeklyScheduleAllowed(cr.getIsWeeklyScheduleAllowed()); + if (nvl(cr.getIsMonthlyScheduleAllowed()).length()>0) + ncr.setIsMonthlyScheduleAllowed(cr.getIsMonthlyScheduleAllowed()); + + ncr.setPageSize(cr.getPageSize()); + ncr.setReportType(cr.getReportType()); + + + DataSourceList dataSourceList = objFactory.createDataSourceList(); + ncr.setDataSourceList(dataSourceList); + + for (Iterator iter = cr.getDataSourceList().getDataSource().iterator(); iter.hasNext();) { + dataSourceList.getDataSource().add( + cloneDataSourceType(objFactory, (DataSourceType) iter.next())); + } + + if (cr.getFormFieldList() != null) { + FormFieldList formFieldList = objFactory.createFormFieldList(); + ncr.setFormFieldList(formFieldList); + ncr.getFormFieldList().setComment(formFieldList.getComment()); + + for (Iterator iter = cr.getFormFieldList().getFormField().iterator(); iter + .hasNext();) + formFieldList.getFormField().add( + cloneFormFieldType(objFactory, (FormFieldType) iter.next())); + formFieldList.setComment(cr.getFormFieldList().getComment()); + } // if + + if (cr.getJavascriptList() != null) { + JavascriptList javascriptList = objFactory.createJavascriptList(); + ncr.setJavascriptList(javascriptList); + + for (Iterator iter = cr.getJavascriptList().getJavascriptItem().iterator(); iter + .hasNext();) + javascriptList.getJavascriptItem().add( + cloneJavascriptType(objFactory, (JavascriptItemType) iter.next())); + } // if + + if (cr.getSemaphoreList() != null) { + SemaphoreList semaphoreList = objFactory.createSemaphoreList(); + ncr.setSemaphoreList(semaphoreList); + + for (Iterator iter = cr.getSemaphoreList().getSemaphore().iterator(); iter + .hasNext();) { + semaphoreList.getSemaphore().add( + cloneSemaphoreType(objFactory, (SemaphoreType) iter.next())); + } + } // if + + if (nvl(cr.getDashboardOptions()).length()>0) + ncr.setDashboardOptions(cr.getDashboardOptions()); + if(cr.isDashboardType()!=null) + ncr.setDashboardType(cr.isDashboardType()); + if(cr.isReportInNewWindow()!=null) + ncr.setReportInNewWindow(cr.isReportInNewWindow()); + ncr.setDisplayFolderTree(cr.isDisplayFolderTree()); + if (cr.getDashBoardReports() == null) { + if (cr.getMaxRowsInExcelDownload()!=null && cr.getMaxRowsInExcelDownload()>0) + ncr.setMaxRowsInExcelDownload(cr.getMaxRowsInExcelDownload()); + } + + if (cr.getDashBoardReports() != null) { + DashboardReports dashboardReports = objFactory.createDashboardReports(); + ncr.setDashBoardReports(dashboardReports); + + for (Iterator iter = cr.getDashBoardReports().getReportsList().iterator(); iter + .hasNext();) { + dashboardReports.getReportsList().add( + cloneDashboardType(objFactory, (Reports) iter.next())); + } + } // if + + if (cr.getChartAdditionalOptions() != null) { + ChartAdditionalOptions chartAdditionalOptions = objFactory.createChartAdditionalOptions(); + if(nvl(cr.getChartAdditionalOptions().getChartMultiplePieOrder()).length()>0) + chartAdditionalOptions.setChartMultiplePieOrder(cr.getChartAdditionalOptions().getChartMultiplePieOrder()); + if(nvl(cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay()).length()>0) + chartAdditionalOptions.setChartMultiplePieLabelDisplay(cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay()); + + if(nvl(cr.getChartAdditionalOptions().getChartOrientation()).length()>0) + chartAdditionalOptions.setChartOrientation(cr.getChartAdditionalOptions().getChartOrientation()); + if(nvl(cr.getChartAdditionalOptions().getSecondaryChartRenderer()).length()>0) + chartAdditionalOptions.setSecondaryChartRenderer(cr.getChartAdditionalOptions().getSecondaryChartRenderer()); + + if(nvl(cr.getChartAdditionalOptions().getChartDisplay()).length()>0) + chartAdditionalOptions.setChartDisplay(cr.getChartAdditionalOptions().getChartDisplay()); + if(nvl(cr.getChartAdditionalOptions().getHideToolTips()).length()>0) + chartAdditionalOptions.setHideToolTips(cr.getChartAdditionalOptions().getHideToolTips()); + if(nvl(cr.getChartAdditionalOptions().getHidechartLegend()).length()>0) + chartAdditionalOptions.setHidechartLegend(cr.getChartAdditionalOptions().getHidechartLegend()); + if(nvl(cr.getChartAdditionalOptions().getLegendPosition()).length()>0) + chartAdditionalOptions.setLegendPosition(cr.getChartAdditionalOptions().getLegendPosition()); + if(nvl(cr.getChartAdditionalOptions().getLabelAngle()).length()>0) + chartAdditionalOptions.setLabelAngle(cr.getChartAdditionalOptions().getLabelAngle()); + + if(nvl(cr.getChartAdditionalOptions().getIntervalFromdate()).length()>0) + chartAdditionalOptions.setIntervalFromdate(cr.getChartAdditionalOptions().getIntervalFromdate()); + if(nvl(cr.getChartAdditionalOptions().getIntervalTodate()).length()>0) + chartAdditionalOptions.setIntervalTodate(cr.getChartAdditionalOptions().getIntervalTodate()); + if(nvl(cr.getChartAdditionalOptions().getIntervalLabel()).length()>0) + chartAdditionalOptions.setIntervalLabel(cr.getChartAdditionalOptions().getIntervalLabel()); + + if(nvl(cr.getChartAdditionalOptions().getLastSeriesALineChart()).length()>0) + chartAdditionalOptions.setLastSeriesALineChart(cr.getChartAdditionalOptions().getLastSeriesALineChart()); + if(nvl(cr.getChartAdditionalOptions().getLastSeriesABarChart()).length()>0) + chartAdditionalOptions.setLastSeriesABarChart(cr.getChartAdditionalOptions().getLastSeriesABarChart()); + + if(nvl(cr.getChartAdditionalOptions().getMaxLabelsInDomainAxis()).length()>0) + chartAdditionalOptions.setMaxLabelsInDomainAxis(cr.getChartAdditionalOptions().getMaxLabelsInDomainAxis()); + if(nvl(cr.getChartAdditionalOptions().getLinearRegression()).length()>0) + chartAdditionalOptions.setLinearRegression(cr.getChartAdditionalOptions().getLinearRegression()); + if(nvl(cr.getChartAdditionalOptions().getLinearRegressionColor()).length()>0) + chartAdditionalOptions.setLinearRegressionColor(cr.getChartAdditionalOptions().getLinearRegressionColor()); + if(nvl(cr.getChartAdditionalOptions().getExponentialRegressionColor()).length()>0) + chartAdditionalOptions.setExponentialRegressionColor(cr.getChartAdditionalOptions().getExponentialRegressionColor()); + if(nvl(cr.getChartAdditionalOptions().getMaxRegression()).length()>0) + chartAdditionalOptions.setMaxRegression(cr.getChartAdditionalOptions().getMaxRegression()); + if(nvl(cr.getChartAdditionalOptions().getRangeAxisUpperLimit()).length()>0) + chartAdditionalOptions.setRangeAxisUpperLimit(cr.getChartAdditionalOptions().getRangeAxisUpperLimit()); + if(nvl(cr.getChartAdditionalOptions().getRangeAxisLowerLimit()).length()>0) + chartAdditionalOptions.setRangeAxisLowerLimit(cr.getChartAdditionalOptions().getRangeAxisLowerLimit()); + if(nvl(cr.getChartAdditionalOptions().getOverlayItemValueOnStackBar()).length()>0) + chartAdditionalOptions.setOverlayItemValueOnStackBar(cr.getChartAdditionalOptions().getOverlayItemValueOnStackBar()); + chartAdditionalOptions.setAnimate((cr.getChartAdditionalOptions().isAnimate()!=null && cr.getChartAdditionalOptions().isAnimate().booleanValue())?true:false); + + if(nvl(cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString()).length()>0) + chartAdditionalOptions.setKeepDomainAxisValueAsString(cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString()); + + + // Animate + chartAdditionalOptions.setAnimateAnimatedChart((cr.getChartAdditionalOptions().isAnimateAnimatedChart()!=null && cr.getChartAdditionalOptions().isAnimateAnimatedChart().booleanValue())?true:false); + chartAdditionalOptions.setStacked((cr.getChartAdditionalOptions().isStacked()!=null && cr.getChartAdditionalOptions().isStacked().booleanValue())?true:false); + chartAdditionalOptions.setBarControls((cr.getChartAdditionalOptions().isBarControls()!=null && cr.getChartAdditionalOptions().isBarControls().booleanValue())?true:false); + chartAdditionalOptions.setXAxisDateType((cr.getChartAdditionalOptions().isXAxisDateType()!=null && cr.getChartAdditionalOptions().isXAxisDateType().booleanValue())?true:false); + chartAdditionalOptions.setLessXaxisTickers((cr.getChartAdditionalOptions().isLessXaxisTickers()!=null && cr.getChartAdditionalOptions().isLessXaxisTickers().booleanValue())?true:false); + chartAdditionalOptions.setTimeAxis((cr.getChartAdditionalOptions().isTimeAxis()!=null && cr.getChartAdditionalOptions().isTimeAxis().booleanValue())?true:false); + + if(nvl(cr.getChartAdditionalOptions().getTimeSeriesRender()).length()>0) + chartAdditionalOptions.setTimeSeriesRender(cr.getChartAdditionalOptions().getTimeSeriesRender()); + + chartAdditionalOptions.setMultiSeries((cr.getChartAdditionalOptions().isMultiSeries()!=null && cr.getChartAdditionalOptions().isMultiSeries().booleanValue())?true:false); + + chartAdditionalOptions.setTopMargin(cr.getChartAdditionalOptions().getTopMargin()!=null?cr.getChartAdditionalOptions().getTopMargin():new Integer(30)); + chartAdditionalOptions.setBottomMargin(cr.getChartAdditionalOptions().getBottomMargin()!=null?cr.getChartAdditionalOptions().getBottomMargin():new Integer(50)); + chartAdditionalOptions.setLeftMargin(cr.getChartAdditionalOptions().getLeftMargin()!=null?cr.getChartAdditionalOptions().getLeftMargin():new Integer(100)); + chartAdditionalOptions.setRightMargin(cr.getChartAdditionalOptions().getRightMargin()!=null?cr.getChartAdditionalOptions().getRightMargin():new Integer(60)); + + + ncr.setChartAdditionalOptions(chartAdditionalOptions); + } // if + + if (nvl(cr.getJavascriptElement()).length()>0) + ncr.setJavascriptElement(cr.getJavascriptElement()); + if (nvl(cr.getFolderId()).length()>0) + ncr.setFolderId(cr.getFolderId()); + + if (cr.getChartDrillOptions() != null) { + ChartDrillOptions chartDrillOptions = objFactory.createChartDrillOptions(); + + if(nvl(cr.getChartDrillOptions().getDrillReportId()).length()>0) + chartDrillOptions.setDrillReportId(cr.getChartDrillOptions().getDrillReportId()); + + for (Iterator iter = cr.getChartDrillOptions().getTargetFormfield().iterator(); iter + .hasNext();) { + chartDrillOptions.getTargetFormfield().add( + cloneChartDrillFormfield(objFactory, (ChartDrillFormfield)iter.next())); + + } + + if(nvl(cr.getChartDrillOptions().getDrillXAxisFormField()).length()>0) + chartDrillOptions.setDrillXAxisFormField(cr.getChartDrillOptions().getDrillXAxisFormField()); + if(nvl(cr.getChartDrillOptions().getDrillYAxisFormField()).length()>0) + chartDrillOptions.setDrillYAxisFormField(cr.getChartDrillOptions().getDrillYAxisFormField()); + if(nvl(cr.getChartDrillOptions().getDrillSeriesFormField()).length()>0) + chartDrillOptions.setDrillSeriesFormField(cr.getChartDrillOptions().getDrillSeriesFormField()); + + + ncr.setChartDrillOptions(chartDrillOptions); + } + + if (nvl(cr.getIsOneTimeScheduleAllowed()).length()>0) + ncr.setIsOneTimeScheduleAllowed(cr.getIsOneTimeScheduleAllowed()); + if (nvl(cr.getIsHourlyScheduleAllowed()).length()>0) + ncr.setIsHourlyScheduleAllowed(cr.getIsHourlyScheduleAllowed()); + if (nvl(cr.getIsDailyScheduleAllowed()).length()>0) + ncr.setIsDailyScheduleAllowed(cr.getIsDailyScheduleAllowed()); + if (nvl(cr.getIsDailyMFScheduleAllowed()).length()>0) + ncr.setIsDailyMFScheduleAllowed(cr.getIsDailyMFScheduleAllowed()); + if (nvl(cr.getIsWeeklyScheduleAllowed()).length()>0) + ncr.setIsWeeklyScheduleAllowed(cr.getIsWeeklyScheduleAllowed()); + if (nvl(cr.getIsMonthlyScheduleAllowed()).length()>0) + ncr.setIsMonthlyScheduleAllowed(cr.getIsMonthlyScheduleAllowed()); + + ncr.setPageSize(cr.getPageSize()); + ncr.setReportType(cr.getReportType()); + + if (cr.getReportMap() != null){ + ReportMap repMap = objFactory.createReportMap(); + if(nvl(cr.getReportMap().getMarkerColor()).length()>0) + repMap.setMarkerColor(cr.getReportMap().getMarkerColor()); + if(nvl(cr.getReportMap().getUseDefaultSize()).length()>0) + repMap.setUseDefaultSize(cr.getReportMap().getUseDefaultSize()); + if(nvl(cr.getReportMap().getHeight()).length()>0) + repMap.setHeight(cr.getReportMap().getHeight()); + if(nvl(cr.getReportMap().getWidth()).length()>0) + repMap.setWidth(cr.getReportMap().getWidth()); + if(nvl(cr.getReportMap().getIsMapAllowedYN()).length()>0) + repMap.setIsMapAllowedYN(cr.getReportMap().getIsMapAllowedYN()); + if(nvl(cr.getReportMap().getAddAddressInDataYN()).length()>0) + repMap.setAddAddressInDataYN(cr.getReportMap().getAddAddressInDataYN()); + if(nvl(cr.getReportMap().getAddressColumn()).length()>0) + repMap.setAddressColumn(cr.getReportMap().getAddressColumn()); + if(nvl(cr.getReportMap().getDataColumn()).length()>0) + repMap.setDataColumn(cr.getReportMap().getDataColumn()); + if(nvl(cr.getReportMap().getDefaultMapType()).length()>0) + repMap.setDefaultMapType(cr.getReportMap().getDefaultMapType()); + if(nvl(cr.getReportMap().getLatColumn()).length()>0) + repMap.setLatColumn(cr.getReportMap().getLatColumn()); + if(nvl(cr.getReportMap().getLongColumn()).length()>0) + repMap.setLongColumn(cr.getReportMap().getLongColumn()); + if(nvl(cr.getReportMap().getColorColumn()).length()>0) + repMap.setColorColumn(cr.getReportMap().getColorColumn()); + if(nvl(cr.getReportMap().getLegendColumn()).length()>0) + repMap.setLegendColumn(cr.getReportMap().getLegendColumn()); + + + for (Iterator iter = cr.getReportMap().getMarkers().iterator(); iter + .hasNext();) { + repMap.getMarkers().add( + cloneMarkerType(objFactory, (Marker)iter.next())); + + } + + ncr.setReportMap(repMap); + } + + + + } catch (JAXBException ex) { // try + throw new RaptorException(ex.getMessage(), ex.getCause()); + } + + return ncr; + } // cloneCustomReport + + /** ************************************************************************************************* */ + + public void printFormatType(FormatType ft) { + System.out.println("------------------------------------------------"); + System.out.println("Semaphore Col Format"); + System.out.println("------------------------------------------------"); + System.out.println("FormatId: [" + ft.getFormatId() + "]"); + System.out.println("LessThanValue: [" + ft.getLessThanValue() + "]"); + System.out.println("Expression: [" + ft.getExpression() + "]"); + System.out.println("Bold: [" + ft.isBold() + "]"); + System.out.println("Italic: [" + ft.isItalic() + "]"); + System.out.println("Underline: [" + ft.isUnderline() + "]"); + System.out.println("BgColor: [" + ft.getBgColor() + "]"); + System.out.println("FontColor: [" + ft.getFontColor() + "]"); + System.out.println("FontFace: [" + ft.getFontFace() + "]"); + System.out.println("FontSize: [" + ft.getFontSize() + "]"); + System.out.println("Alignment: [" + ft.getAlignment() + "]"); + System.out.println("Comment: [" + ft.getComment() + "]"); + System.out.println("------------------------------------------------"); + } // printFormatType + + public void printSemaphoreType(SemaphoreType st) { + System.out.println("------------------------------------------------"); + System.out.println("Semaphore"); + System.out.println("------------------------------------------------"); + System.out.println("SemaphoreId: [" + st.getSemaphoreId() + "]"); + System.out.println("SemaphoreName: [" + st.getSemaphoreName() + "]"); + System.out.println("SemaphoreType: [" + st.getSemaphoreType() + "]"); + System.out.println("Comment: [" + st.getComment() + "]"); + + if (st.getFormatList() != null) + for (Iterator iter = st.getFormatList().getFormat().iterator(); iter.hasNext();) + printFormatType((FormatType) iter.next()); + + System.out.println("------------------------------------------------"); + } // printSemaphoreType + + public void printFormFieldType(FormFieldType fft) { + System.out.println("------------------------------------------------"); + System.out.println("Form Field"); + System.out.println("------------------------------------------------"); + System.out.println("FieldId: [" + fft.getFieldId() + "]"); + System.out.println("ColId: [" + fft.getColId() + "]"); + System.out.println("FieldName: [" + fft.getFieldName() + "]"); + System.out.println("FieldType: [" + fft.getFieldType() + "]"); + System.out.println("ValidationType: [" + fft.getValidationType() + "]"); + System.out.println("Mandatory: [" + fft.getMandatory() + "]"); + System.out.println("DefaultValue: [" + fft.getDefaultValue() + "]"); + System.out.println("OrderBySeq: [" + fft.getOrderBySeq() + "]"); + System.out.println("FieldSQL: [" + fft.getFieldSQL() + "]"); + System.out.println("Comment: [" + fft.getComment() + "]"); + if (fft.getPredefinedValueList() != null) + for (Iterator iter = fft.getPredefinedValueList().getPredefinedValue().iterator(); iter + .hasNext();) + System.out.println("PredefinedValues: [" + ((String) iter.next()) + "]"); + + System.out.println("------------------------------------------------"); + } // printFormFieldType + + public void printColFilterType(ColFilterType cft) { + System.out.println("------------------------------------------------"); + System.out.println("Col Filter"); + System.out.println("------------------------------------------------"); + System.out.println("ColId: [" + cft.getColId() + "]"); + System.out.println("FilterSeq: [" + cft.getFilterSeq() + "]"); + System.out.println("JoinCondition: [" + cft.getJoinCondition() + "]"); + System.out.println("OpenBrackets: [" + cft.getOpenBrackets() + "]"); + System.out.println("Expression: [" + cft.getExpression() + "]"); + System.out.println("ArgType: [" + cft.getArgType() + "]"); + System.out.println("ArgValue: [" + cft.getArgValue() + "]"); + System.out.println("CloseBrackets: [" + cft.getCloseBrackets() + "]"); + System.out.println("Comment: [" + cft.getComment() + "]"); + System.out.println("------------------------------------------------"); + } // printColFilterType + + public void printDataColumnType(DataColumnType dct) { + System.out.println("------------------------------------------------"); + System.out.println("Data Column"); + System.out.println("------------------------------------------------"); + System.out.println("ColId: [" + dct.getColId() + "]"); + System.out.println("TableId: [" + dct.getTableId() + "]"); + System.out.println("DbColName: [" + dct.getDbColName() + "]"); + System.out.println("CrossTabValue: [" + dct.getCrossTabValue() + "]"); + System.out.println("ColName: [" + dct.getColName() + "]"); + System.out.println("DisplayName: [" + dct.getDisplayName() + "]"); + System.out.println("DisplayWidth: [" + dct.getDisplayWidth() + "]"); + System.out.println("DisplayAlignment: [" + dct.getDisplayAlignment() + "]"); + System.out.println("DisplayHeaderAlignment: [" + dct.getDisplayHeaderAlignment() + "]"); + System.out.println("OrderSeq(): [" + dct.getOrderSeq() + "]"); + System.out.println("Visible: [" + dct.isVisible() + "]"); + System.out.println("Calculated: [" + dct.isCalculated() + "]"); + System.out.println("ColType: [" + dct.getColType() + "]"); + System.out.println("ColFormat: [" + dct.getColFormat() + "]"); + System.out.println("GroupBreak: [" + dct.isGroupBreak() + "]"); + System.out.println("OrderBySeq: [" + dct.getOrderBySeq() + "]"); + System.out.println("OrderByAscDesc: [" + dct.getOrderByAscDesc() + "]"); + System.out.println("DisplayTotal: [" + dct.getDisplayTotal() + "]"); + System.out.println("ColOnChart: [" + dct.getColOnChart() + "]"); + System.out.println("ChartSeq: [" + dct.getChartSeq() + "]"); + System.out.println("ChartColor: [" + dct.getChartColor() + "]"); + System.out.println("DrillDownType: [" + dct.getDrillDownType() + "]"); + System.out.println("DrillDownURL: [" + dct.getDrillDownURL() + "]"); + System.out.println("DrillDownParams: [" + dct.getDrillDownParams() + "]"); + System.out.println("Comment: [" + dct.getComment() + "]"); + + if (dct.getColFilterList() != null) + for (Iterator iter = dct.getColFilterList().getColFilter().iterator(); iter + .hasNext();) + printColFilterType((ColFilterType) iter.next()); + + System.out.println("SemaphoreId: [" + dct.getSemaphoreId() + "]"); + System.out.println("DbColType: [" + dct.getDbColType() + "]"); + System.out.println("------------------------------------------------"); + } // printDataColumnType + + public void printDataSourceType(DataSourceType dst) { + System.out.println("------------------------------------------------"); + System.out.println("Data Source"); + System.out.println("------------------------------------------------"); + System.out.println("TableId: [" + dst.getTableId() + "]"); + System.out.println("TableName: [" + dst.getTableName() + "]"); + System.out.println("TablePK: [" + dst.getTablePK() + "]"); + System.out.println("DisplayName: [" + dst.getDisplayName() + "]"); + System.out.println("RefTableId: [" + dst.getRefTableId() + "]"); + System.out.println("RefDefinition: [" + dst.getRefDefinition() + "]"); + System.out.println("Comment: [" + dst.getComment() + "]"); + + for (Iterator iter = dst.getDataColumnList().getDataColumn().iterator(); iter + .hasNext();) + printDataColumnType((DataColumnType) iter.next()); + + System.out.println("------------------------------------------------"); + } // printDataSourceType + + public void print() { + System.out.println("------------------------------------------------"); + System.out.println("ReportWrapper object"); + System.out.println("------------------------------------------------"); + System.out.println("PageSize: [" + getPageSize() + "]"); + System.out.println("ReportType: [" + getReportType() + "]"); + System.out.println("ReportName: [" + getReportName() + "]"); + System.out.println("ReportDescr: [" + getReportDescr() + "]"); + System.out.println("ChartType: [" + getChartType() + "]"); + System.out.println("ChartTypeFixed: [" + getChartTypeFixed() + "]"); + //System.out.println("ChartLeftAxisLabel: [" + getChartLeftAxisLabel() + "]"); + //System.out.println("ChartRightAxisLabel: [" + getChartRightAxisLabel() + "]"); + System.out.println("ChartWidth: [" + getChartWidth() + "]"); + System.out.println("ChartHeight: [" + getChartHeight() + "]"); + System.out.println("Public: [" + isPublic() + "]"); + System.out.println("CreateId: NOT USED ANYMORE[" + /* getCreateId()+ */"]"); + System.out.println("CreateDate: NOT USED ANYMORE[" + /* getCreateDate()+ */"]"); + System.out.println("ReportSQL: [" + getReportSQL() + "]"); + System.out.println("ReportTitle: [" + getReportTitle() + "]"); + System.out.println("DbInfo: [" + getDBInfo() + "]"); + System.out.println("ReportSubTitle: [" + getReportSubTitle() + "]"); + System.out.println("ReportHeader: [" + getReportHeader() + "]"); + System.out.println("ReportFooter: [" + getReportFooter() + "]"); + System.out.println("NumFormCols: [" + getNumFormCols() + "]"); + System.out.println("DisplayOptions: [" + getDisplayOptions() + "]"); + System.out.println("Comment: [" + getComment() + "]"); + + for (Iterator iter = cr.getDataSourceList().getDataSource().iterator(); iter.hasNext();) + printDataSourceType((DataSourceType) iter.next()); + + if (cr.getFormFieldList() != null) + for (Iterator iter = cr.getFormFieldList().getFormField().iterator(); iter + .hasNext();) + printFormFieldType((FormFieldType) iter.next()); + + if (cr.getSemaphoreList() != null) + for (Iterator iter = cr.getSemaphoreList().getSemaphore().iterator(); iter + .hasNext();) + printSemaphoreType((SemaphoreType) iter.next()); + + System.out.println("------------------------------------------------"); + System.out.println("ReportWrapper object end"); + System.out.println("------------------------------------------------"); + } // print + + private int getIntValue(String value, int defaultValue) { + int iValue = defaultValue; + try { + iValue = Integer.parseInt(value); + } catch (Exception e) { + } + + return iValue; + } // getIntValue + public static String replaceNewLine( String strSource, String strFind, String chrReplace ) + { + // buffer to hold the target string after replacement is done. + StringBuffer sbfTemp = new StringBuffer(); + + try + { + // for each occurrence of strFind in strSource, replace it with chrReplace. + int intIndex = strSource.indexOf( strFind, 0 ); + + // check if there is any instace of strFind in strSource + if( intIndex >= 0 ) + { + // holds the index from where the search is supposed to happen. + int intStart = 0; + + // size of the source string + int intTotalSize = strSource.length(); + + while( intStart < intTotalSize && + ( ( intIndex = strSource.indexOf( strFind, intStart ) ) >= 0 ) ) + { + // check if strFind is at the beginning... i.e., at index intStart + if( intIndex == intStart ) + { + /* + * starts with strFind...just append chrReplace + * to the target + */ + sbfTemp.append( chrReplace ); + } + else + { + // append the sub-string...plus chrReplace + sbfTemp.append( strSource.substring( intStart, intIndex ) ); + sbfTemp.append( chrReplace ); + } + + // advance string index + intStart = intIndex + strFind.length(); + } + + // append the last portion of the source string. + sbfTemp.append( strSource.substring( intStart ) ); + } + else + { + // strFind not found... just copy the text as it is. + sbfTemp.append( strSource ); + } + } + catch( Exception expGeneral ) + { + // in case of any exception, return the source string as it is. + sbfTemp = new StringBuffer( strSource ); + } + + return sbfTemp.toString(); + } + + /*folder id*/ + public String getFolderId() { + return nvl(cr.getFolderId()).length()>0?cr.getFolderId():"NULL"; + } + public void setFolderId(String folderId ) { + cr.setFolderId(folderId); + } + + public String addZero(String num) { + int numInt = 0; + try { + numInt = Integer.parseInt(num); + }catch(NumberFormatException ex){ + numInt = 0; + } + if(numInt < 10) return "0"+numInt; + else return ""+numInt; + } + + public String getIsDailyMFScheduleAllowed() { + return cr.getIsDailyMFScheduleAllowed(); + } + + public void setIsDailyMFScheduleAllowed(String isDailyMFScheduleAllowed) { + cr.setIsDailyMFScheduleAllowed(isDailyMFScheduleAllowed); + } + + public String getIsDailyScheduleAllowed() { + return cr.getIsDailyScheduleAllowed(); + } + + public void setIsDailyScheduleAllowed(String isDailyScheduleAllowed) { + cr.setIsDailyScheduleAllowed(isDailyScheduleAllowed); + } + + public String getIsHourlyScheduleAllowed() { + return cr.getIsHourlyScheduleAllowed(); + } + + public void setIsHourlyScheduleAllowed(String isHourlyScheduleAllowed) { + cr.setIsHourlyScheduleAllowed(isHourlyScheduleAllowed); + } + + public String getIsMonthlyScheduleAllowed() { + return cr.getIsMonthlyScheduleAllowed(); + } + + public void setIsMonthlyScheduleAllowed(String isMonthlyScheduleAllowed) { + cr.setIsMonthlyScheduleAllowed(isMonthlyScheduleAllowed); + } + + public String getIsOneTimeScheduleAllowed() { + return cr.getIsOneTimeScheduleAllowed(); + } + + public void setIsOneTimeScheduleAllowed(String isOneTimeScheduleAllowed) { + cr.setIsOneTimeScheduleAllowed(isOneTimeScheduleAllowed); + } + + public String getIsWeeklyScheduleAllowed() { + return cr.getIsWeeklyScheduleAllowed(); + } + + public void setIsWeeklyScheduleAllowed(String isWeeklyScheduleAllowed) { + cr.setIsWeeklyScheduleAllowed(isWeeklyScheduleAllowed); + + } + + public static boolean isNull(String a) { + if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null")) + return true; + else + return false; + } + + public int getDependsOnFormFieldFlag(DataColumnType dc, HashMap formValues) { + int flag = 0; + String fieldValue = ""; + if(nvl(dc.getDependsOnFormField()).length()>0 && nvl(dc.getDependsOnFormField()).indexOf("[")!=-1) { + if(formValues != null) { + Set set = formValues.entrySet(); + String value = ""; + for(Iterator iter1 = set.iterator(); iter1.hasNext(); ) { + Map.Entry entry = (Entry) iter1.next(); + value = (String) entry.getValue(); + if (dc.getDependsOnFormField().equals("["+entry.getKey()+"]")) { + fieldValue = nvl(value); + + if (fieldValue.length()>0 && !fieldValue.equals("NULL")) { + flag = 0; + } else { + flag = 1; + } + + } + } + } + } + + return flag; + } + + /* Datamining Getter Setter */ + + public String getClassifier() { + return (cr.getDataminingOptions()!=null?cr.getDataminingOptions().getClassifier():""); + } + + public void setClassifier( String classifier) { + cr.getDataminingOptions().setClassifier(classifier); + } + + + public int getForecastingPeriod() { + return (cr.getDataminingOptions()!=null? new Integer(cr.getDataminingOptions().getForecastingUnits()).intValue():-1); + } + + public void setForecastingPeriod( String period) { + cr.getDataminingOptions().setForecastingUnits(period); + } + + public String getForecastingTimeFormat() { + return (cr.getDataminingOptions()!=null?cr.getDataminingOptions().getTimeformat():""); + } + + public void setForecastingTimeFormat( String format) { + cr.getDataminingOptions().setTimeformat(format); + } + + /** + * Get Number of Columns to Frozen in Data Grid + */ + + public int getFrozenColumns() { + return cr.getFrozenColumns()==null?0:cr.getFrozenColumns(); + } + + public String getFrozenColumnId() { + int noOfColumns = cr.getFrozenColumns()==null?0:cr.getFrozenColumns(); + if(noOfColumns != 0) { + List reportCols = getOnlyVisibleColumns(); + int colIdx = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + ++colIdx; + DataColumnType dc = (DataColumnType) iter.next(); + if(colIdx == noOfColumns) { + + return dc.getColId(); + } else continue; + } // for + return ""; + } else return ""; + + } + + /** + * Set Number of Columns to Frozen in Data Grid + */ + + public void setFrozenColumns( int frozenColumns) { + cr.setFrozenColumns(frozenColumns); + } + + /** + * @return the reportSQLWithRowNum for ZK Support + */ + public String getReportSQLWithRowNum() { + return reportSQLWithRowNum; + } + + /** + * @param reportSQLWithRowNum the reportSQLWithRowNum to set for ZK Support + */ + public void setReportSQLWithRowNum(String reportSQLWithRowNum) { + this.reportSQLWithRowNum = reportSQLWithRowNum; + } + + //used for Zk sort + public void setReportSQLOnlyFirstPart(String reportSQLOnlyFirstPart) { + this.reportSQLOnlyFirstPart = reportSQLOnlyFirstPart; + } + + public String getReportSQLOnlyFirstPart() { + return this.reportSQLOnlyFirstPart; + } + + public String getTemplateFile() throws RaptorException { + return ReportLoader.getTemplateFile(getReportID()); + } + + public String getPdfImg() { + return cr.getPdfImgLogo(); + } + + + public String getEmptyMessage() { + String emptyMessage = cr.getEmptyMessage(); + if(nvl(emptyMessage).length()<=0) + emptyMessage = Globals.getReportEmptyMessage(); + return emptyMessage; + } + + public void setPdfImg(String img_loc) { + cr.setPdfImgLogo(img_loc); + } + + public void setEmptyMessage(String emptyMessage) { + cr.setEmptyMessage(emptyMessage); + } + + public void setDrillReportIdForChart(String reportId) { + //(cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().setDrillReportId():""; + cr.getChartDrillOptions().setDrillReportId(reportId); + } + + public String getDrillReportIdForChart() { + return (cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().getDrillReportId():""; + } + + public void setDrillXAxisFormField(String formField) { + //(cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().setDrillReportId():""; + cr.getChartDrillOptions().setDrillXAxisFormField(formField); + } + + public String getDrillXAxisFormField() { + return (cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().getDrillXAxisFormField():""; + } + + public void setDrillYAxisFormField(String formField) { + //(cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().setDrillReportId():""; + cr.getChartDrillOptions().setDrillYAxisFormField(formField); + } + + public String getDrillYAxisFormField() { + return (cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().getDrillYAxisFormField():""; + } + + public void setDrillSeriesFormField(String formField) { + //(cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().setDrillReportId():""; + cr.getChartDrillOptions().setDrillSeriesFormField(formField); + } + + public String getDrillSeriesFormField() { + return (cr.getChartDrillOptions()!=null)?cr.getChartDrillOptions().getDrillSeriesFormField():""; + } + + public boolean isEnhancedPaginationNeeded() { + List reportCols = getAllColumns(); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.isEnhancedPagination()!=null && dc.isEnhancedPagination().booleanValue()) + return true; + } // for + return false; + } + + public DataColumnType getColumnWhichNeedEnhancedPagination() { + List reportCols = getAllColumns(); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if (dc.isEnhancedPagination()!=null && dc.isEnhancedPagination().booleanValue()) + return dc; + } // for + return null; + } + + public void setDataGridAlign(String align) { + cr.setDataGridAlign(align); + } + + + public String getDataGridAlign() { + return (cr.getDataGridAlign()!=null)?cr.getDataGridAlign():"left"; + } + + public void setWidthNoColumn(String width) { + cr.setWidthNoColumn(width); + } + + + public String getWidthNoColumn() { + return (cr.getWidthNoColumn()!=null)?cr.getWidthNoColumn():"30px"; + } + + public void setWholeSQL(String sql) { + wholeSQL = sql; + } + public String getWholeSQL() { + return wholeSQL; + } + +} // ReportWrapper diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DBColumnInfo.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DBColumnInfo.java new file mode 100644 index 00000000..4496fdca --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DBColumnInfo.java @@ -0,0 +1,76 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.RaptorObject; + +public class DBColumnInfo extends RaptorObject { + private String tableName = null; + + private String colName = null; + + private String colType = null; + + private String label = null; + + // public DBColumnInfo() {} + + public DBColumnInfo(String tableName, String colName, String colType, String label) { + super(); + + setTableName(tableName); + setColName(colName); + setColType(colType); + setLabel(label); + } // DBColumnInfo + + public String getTableName() { + return tableName; + } + + public String getColName() { + return colName; + } + + public String getColType() { + return colType; + } + + public String getLabel() { + return label; + } + + private void setTableName(String tableName) { + this.tableName = tableName; + } + + private void setColName(String colName) { + this.colName = colName; + } + + private void setColType(String colType) { + this.colType = colType; + } + + public void setLabel(String label) { + this.label = label; + } + +} // DBColumnInfo diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DrillDownParamDef.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DrillDownParamDef.java new file mode 100644 index 00000000..8972e54a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/DrillDownParamDef.java @@ -0,0 +1,111 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.RaptorObject; + +public class DrillDownParamDef extends RaptorObject { + private String fieldName = ""; + + private String valType = "0"; + + private String valValue = ""; + + private String valColId = ""; + + private String valFieldId = ""; + + public DrillDownParamDef(String drillDownParamStr) { + super(); + + drillDownParamStr = nvl(drillDownParamStr).trim(); + if (drillDownParamStr.indexOf('=') >= 0) { + fieldName = drillDownParamStr.substring(0, drillDownParamStr.indexOf('=')); + + if (drillDownParamStr.length() > drillDownParamStr.indexOf('=') + 2 + && drillDownParamStr.charAt(drillDownParamStr.indexOf('=') + 1) == '[' + && drillDownParamStr.charAt(drillDownParamStr.length() - 1) == ']') { + drillDownParamStr = drillDownParamStr.substring( + drillDownParamStr.indexOf('=') + 2, drillDownParamStr.length() - 1); + + if (drillDownParamStr.indexOf('!') < 0) + valColId = drillDownParamStr; + else if (drillDownParamStr.indexOf('!') == 0) + valFieldId = drillDownParamStr.substring(1); + else { + valColId = drillDownParamStr.substring(0, drillDownParamStr.indexOf('!')); + valFieldId = drillDownParamStr + .substring(drillDownParamStr.indexOf('!') + 1); + } // else + + if (valColId.length() > 0 && valFieldId.length() > 0) + valType = "4"; + else if (valFieldId.length() > 0) + valType = "3"; + else if (valColId.length() > 0) + valType = "2"; + } else { + valType = "1"; + valValue = drillDownParamStr.substring(drillDownParamStr.indexOf('=') + 1); + } // else + } // if + } // DrillDownParamDef + + public String getFieldName() { + return fieldName; + } + + public String getValType() { + return valType; + } + + public String getValValue() { + return valValue; + } + + public String getValColId() { + return valColId; + } + + public String getValFieldId() { + return valFieldId; + } + + private void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + private void setValType(String valType) { + this.valType = valType; + } + + private void setValValue(String valValue) { + this.valValue = valValue; + } + + private void setValColId(String valColId) { + this.valColId = valColId; + } + + private void setValFieldId(String valFieldId) { + this.valFieldId = valFieldId; + } + +} // DrillDownParamDef diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/Marker.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/Marker.java new file mode 100644 index 00000000..a9d9be85 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/Marker.java @@ -0,0 +1,79 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.RaptorObject; + +public class Marker extends RaptorObject { + String markerColor = ""; + String addressColumn = ""; + String dataColumn = ""; + String address = ""; + String data = ""; + String color = ""; + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Marker(String markerColor, String addressColumn, String dataColumn){ + this.setMarkerColor(markerColor); + this.setAddressColumn(addressColumn); + this.setDataColumn(dataColumn); + } + + public String getAddressColumn() { + return addressColumn; + } + public void setAddressColumn(String addressColumn) { + this.addressColumn = addressColumn; + } + public String getDataColumn() { + return dataColumn; + } + public void setDataColumn(String dataColumn) { + this.dataColumn = dataColumn; + } + public String getMarkerColor() { + return markerColor; + } + public void setMarkerColor(String markerColor) { + this.markerColor = markerColor; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportDefinition.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportDefinition.java new file mode 100644 index 00000000..9d66717a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportDefinition.java @@ -0,0 +1,1471 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import java.io.Serializable; +import java.sql.Connection; +import java.util.Calendar; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.StringTokenizer; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.xml.bind.JAXBException; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +//import javax.xml.transform.stream.*; + +import org.openecomp.portalsdk.analytics.controller.WizardSequence; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceCrossTab; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceDashboard; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceLinear; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceSQLBasedCrossTab; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceSQLBasedHive; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceSQLBasedLinear; +import org.openecomp.portalsdk.analytics.controller.WizardSequenceSQLBasedLinearDatamining; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.DataCache; +import org.openecomp.portalsdk.analytics.model.ReportLoader; +import org.openecomp.portalsdk.analytics.model.base.OrderBySeqComparator; +import org.openecomp.portalsdk.analytics.model.base.OrderSeqComparator; +import org.openecomp.portalsdk.analytics.model.base.ReportWrapper; +import org.openecomp.portalsdk.analytics.model.runtime.FormField; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.DbUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.xmlobj.ChartAdditionalOptions; +import org.openecomp.portalsdk.analytics.xmlobj.ChartDrillOptions; +import org.openecomp.portalsdk.analytics.xmlobj.ColFilterType; +import org.openecomp.portalsdk.analytics.xmlobj.CustomReportType; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnList; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.DataSourceType; +import org.openecomp.portalsdk.analytics.xmlobj.DataminingOptions; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldList; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.analytics.xmlobj.FormatList; +import org.openecomp.portalsdk.analytics.xmlobj.FormatType; +import org.openecomp.portalsdk.analytics.xmlobj.JavascriptItemType; +import org.openecomp.portalsdk.analytics.xmlobj.ObjectFactory; +import org.openecomp.portalsdk.analytics.xmlobj.PredefinedValueList; +import org.openecomp.portalsdk.analytics.xmlobj.SemaphoreType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +/**
+ * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting)
+ *
+ * + * --------------------------------------------------------------------------------------------------
+ * ReportDefinition.java - This involves in creating and modifying RAPTOR reports. + * --------------------------------------------------------------------------------------------------
+ * + * + * Change Log

+ * + * 18-Aug-2009 : Version 8.5.1 (Sundar);
  • request Object is passed to prevent caching user/roles - Datamining/Hosting.
+ * 27-Jul-2009 : Version 8.4 (Sundar);
  • userIsAuthorizedToSeeLog is checked for Admin User instead of Super User.
+ * 22-Jun-2009 : Version 8.4 (Sundar);
  • A new type ChartAdditionalOptions is introduced in RAPTOR XSD. + * For this type a create procedure is added to this class.
+ * + */ + +public class ReportDefinition extends ReportWrapper implements Serializable { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportDefinition.class); + + + private ReportSchedule reportSchedule = null; + + private WizardSequence wizardSequence = null; + + + private boolean reportUpdateLogged = false; // Used to avoid multiple + // entries in the report log + // when persisting report on + // each step + + private ReportDefinition(CustomReportType crType, String reportID, String ownerID, + String createID, String createDate, String updateID, String updateDate, + String menuID, boolean menuApproved, HttpServletRequest request) throws RaptorException { + super(crType, reportID, ownerID, createID, createDate, updateID, updateDate, menuID, + menuApproved); + if(reportID.equals("-1")) + reportSchedule = new ReportSchedule(getReportID(), getOwnerID(), false, request); + else + reportSchedule = new ReportSchedule(getReportID(), getOwnerID(), true, request); + generateWizardSequence(null); + } // ReportDefinition + + public ReportDefinition(ReportWrapper rw, HttpServletRequest request)throws RaptorException { + super(rw); + + reportSchedule = new ReportSchedule(reportID, rw.getOwnerID(),false, request); + generateWizardSequence(null); + } // ReportDefinition + + private void setReportID(String reportID) { + this.reportID = reportID; + reportSchedule.setReportID(reportID); + reportSchedule.setScheduleUserID(getOwnerID()); + } // setReportID + + public ReportSchedule getReportSchedule() { + return reportSchedule; + } + + public static ReportDefinition unmarshal(String reportXML, String reportID, HttpServletRequest request) + throws RaptorException { + ReportDefinition rn = null; + CustomReportType crType = ReportWrapper.unmarshalCR(reportXML); + //Log.write("Report [" + reportID + "]: XML unmarshalled", 4); + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML unmarshalled")); + + rn = new ReportDefinition(crType, reportID, null, null, null, null, null, null, false, request); + return rn; + } // unmarshal + + public static ReportDefinition createBlank(HttpServletRequest request) throws RaptorException { + String curTime = Utils.getCurrentDateTime(); + String userID = AppUtils.getUserID(request); + ReportDefinition rd = new ReportDefinition(ReportWrapper.createBlankCR(userID), "-1", + userID, userID, curTime, userID, curTime, "", false, request); + + // Necessary initialization + + return rd; + } // ReportDefinition + + public void setAsCopy(HttpServletRequest request) throws RaptorException { + verifySQLBasedReportAccess(request); + + replaceCustomReportWithClone(); + + setReportID("-1"); + setReportName("Copy: " + getReportName()); + } // setAsCopy + + public WizardSequence getWizardSequence() { + return wizardSequence; + } // getWizardSequence + + public void generateWizardSequence(HttpServletRequest request) throws RaptorException { + boolean userIsAuthorizedToSeeLog = false; + String userId = null; + if(request!=null) { + userId = AppUtils.getUserID(request); + if (userId != null) + userIsAuthorizedToSeeLog = AppUtils.isAdminUser(request) + || AppUtils.isAdminUser(request); + //System.out.println("******** Report Type "+getReportType() + " userIsAuthorizedToSeeLog " + userIsAuthorizedToSeeLog); + } + if (getReportType().equals(AppConstants.RT_LINEAR)){ + if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) + wizardSequence = new WizardSequenceSQLBasedLinear(userIsAuthorizedToSeeLog); + else if (getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN)) + wizardSequence = new WizardSequenceSQLBasedLinearDatamining(userIsAuthorizedToSeeLog); + else + wizardSequence = new WizardSequenceLinear(userIsAuthorizedToSeeLog); + } else if (getReportType().equals(AppConstants.RT_CROSSTAB)) { + if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) + wizardSequence = new WizardSequenceSQLBasedCrossTab(userIsAuthorizedToSeeLog); + else + wizardSequence = new WizardSequenceCrossTab(userIsAuthorizedToSeeLog); + } else if (getReportType().equals(AppConstants.RT_DASHBOARD)) { + wizardSequence = new WizardSequenceDashboard(userIsAuthorizedToSeeLog); + } else if (getReportType().equals(AppConstants.RT_HIVE)) { + wizardSequence = new WizardSequenceSQLBasedHive(userIsAuthorizedToSeeLog); + } else + wizardSequence = new WizardSequence(); + } // generateWizardSequence + + private boolean canPersistDashboard() { + //System.out.println(" getDashBoardReports().getReportsList().size() " + getDashBoardReports().getReportsList().size()); + /* Commented for New DashBoard + if (getDashBoardReports()!=null && getDashBoardReports().getReportsList()!=null && getDashBoardReports().getReportsList().size() > 0) { + for (Iterator iter = getDashBoardReports().getReportsList().iterator(); iter.hasNext();) { + Reports report = (Reports)iter.next(); + try { + if(Integer.parseInt(report.getReportId())>0) return true; + } catch (NumberFormatException ex) {} + } // for + } //if + */ + + //if( ) + return nvl(getDashboardLayoutHTML()).length() > 0; + } //canPersistDashboard + + private boolean canPersistLinearReport() { + System.out.println("&&&&&&&&&&&&&&&&&&&&&& canPersistLinearReport"); + boolean visibleColExist = false; + + if (getDataSourceList().getDataSource().size() > 0) { + for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (dct.isVisible()) { + visibleColExist = true; + break; + } + } // for + } // if + + System.out.println("&&&&&&&&&&&&&&&&&&&&&& visibleColExist " + visibleColExist); + return visibleColExist; + } // canPersistLinearReport + + private boolean canPersistCrossTabReport() { + boolean rowColExist = false; + boolean colColExist = false; + boolean valColExist = false; + + if (getDataSourceList().getDataSource().size() > 0) { + for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW)) + rowColExist = true; + if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) + colColExist = true; + if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) + valColExist = true; + } // for + } // if + + return rowColExist && colColExist && valColExist; + } // canPersistCrossTabReport + + private boolean canPersistReport() { + return getReportType().equals(AppConstants.RT_CROSSTAB) ? canPersistCrossTabReport() + : (getReportType().equals(AppConstants.RT_LINEAR)? canPersistLinearReport():((getReportType().equals(AppConstants.RT_HIVE)? canPersistLinearReport():canPersistDashboard()))); + } // canPersistReport + + public void persistReport(HttpServletRequest request) throws RaptorException { + if (!canPersistReport()) { + System.out.println("&&&&&&&&&&&&&&&&&&&&&& In !canPersistReport ReportType: " + getReportType()); + return; + } else { + System.out.println("&&&&&&&&&&&&&&&&&&&&&& Not In !canPersistReport"); + } + + Connection connection = null; + try { + String userID = AppUtils.getUserID(request); + String reportXML = marshal(); + logger.debug(EELFLoggerDelegate.debugLogger, ("Ocurring during Schedule ")); + System.out.println("&&&&&&&&&&&&&&&&&&&&&& Report ID " + reportID); + if (nvl(reportID, "-1").equals("-1")) { + connection = DbUtils.startTransaction(); + // Add report + String sql = ""; + if (nvl(Globals.getAdhocReportSequence()).length()> 0 && nvl(Globals.getAdhocUserRoldId()).length() > 0 && AppUtils.isUserInRole(request, Globals.getAdhocUserRoldId()) && !AppUtils.isAdminUser(request)) { + //sql = "SELECT "+ Globals.getAdhocReportSequence() + ".nextval FROM dual"; + sql = Globals.getPersistReportAdhoc(); + sql = sql.replace("[Globals.getAdhocReportSequence()]", Globals.getAdhocReportSequence()); + + } else{ + //sql = "SELECT seq_cr_report.nextval FROM dual"; + sql = Globals.getNewReportData(); + } + DataSet ds = DbUtils.executeQuery(connection,sql); + setReportID(ds.getString(0, 0)); + + reportSecurity.reportCreate(reportID, userID, isPublic()); + ReportLoader.createCustomReportRec(connection, this, reportXML); + ReportLoader.createReportLogEntry(connection, reportID, userID, + AppConstants.RLA_CREATE, "", ""); + reportUpdateLogged = true; + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB insert report " + reportID + " succesfull")); + } else { + // Update report + verifySQLBasedReportAccess(request); + reportSecurity.reportUpdate(request); + connection = DbUtils.startTransaction(); + ReportLoader.updateCustomReportRec(connection, this, reportXML); + if (!reportUpdateLogged) { + ReportLoader.createReportLogEntry(connection, reportID, userID, + AppConstants.RLA_UPDATE,"",""); + reportUpdateLogged = true; + } // if + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " succesfull")); + } + + getReportSchedule().persistScheduleData(connection, request); + + DbUtils.commitTransaction(connection); + } catch (RaptorException e) { + e.printStackTrace(); + DbUtils.rollbackTransaction(connection); + throw e; + } finally { + DbUtils.clearConnection(connection); + } + } // persistReport + + public String getCrossTabDisplayValue(String crossTabValue) { + return nvl(crossTabValue).equals(AppConstants.CV_ROW) ? "Row headings" : (nvl( + crossTabValue).equals(AppConstants.CV_COLUMN) ? "Column headings" : (nvl( + crossTabValue).equals(AppConstants.CV_VALUE) ? "Report values" : "Invisible/Filter")); + } // getCrossTabDisplayValue + + public String getCrossTabDisplayValue(DataColumnType dct) { + return getCrossTabDisplayValue(dct.getCrossTabValue()); + } // getCrossTabDisplayValue + + public String getColumnLabel(DataColumnType dct) throws Exception { + String tableName = getTableById(dct.getTableId()).getTableName(); + Vector dbColumns = null; + dbColumns = DataCache.getReportTableDbColumns(tableName, cr.getDbInfo()); + if (dbColumns != null) + for (int i = 0; i < dbColumns.size(); i++) { + DBColumnInfo dbCol = (DBColumnInfo) dbColumns.get(i); + if (dct.getDbColName().equals(dbCol.getColName())) + return dbCol.getLabel(); + } // for + + return ""; + } // getCrossTabDisplayValue + + public String getFilterLabel(ColFilterType cft) { + StringBuffer fLabel = new StringBuffer(); + + fLabel.append(cft.getExpression()); + fLabel.append(" "); + if (cft.getArgType() != null) + if (cft.getArgType().equals(AppConstants.AT_FORMULA)) { + fLabel.append("[" + cft.getArgValue() + "]"); + } else if (cft.getArgType().equals(AppConstants.AT_VALUE)) { + fLabel.append(cft.getArgValue()); + } else if (cft.getArgType().equals(AppConstants.AT_LIST)) { + fLabel.append("(" + cft.getArgValue() + ")"); + } else if (cft.getArgType().equals(AppConstants.AT_COLUMN)) { + DataColumnType dctFilter = getColumnById(cft.getArgValue()); + fLabel.append("[" + dctFilter.getDisplayName() + "]"); + } else if (cft.getArgType().equals(AppConstants.AT_FORM)) { + fLabel.append("[Form Field]"); + } + + return fLabel.toString(); + } // getFilterLabel + + public Vector getReportUsers(HttpServletRequest request) throws RaptorException { + return reportSecurity.getReportUsers(request); + } // getReportUsers + + public Vector getReportRoles(HttpServletRequest request) throws RaptorException { + return reportSecurity.getReportRoles(request); + } // getReportRoles + + /** ************************************************************************************************* */ + + public void clearAllDrillDowns() { + List reportCols = getAllColumns(); + for (int i = 0; i < reportCols.size(); i++) { + DataColumnType dct = (DataColumnType) reportCols.get(i); + dct.setDrillDownURL(null); + dct.setDrillDownParams(null); + dct.setDrillDownType(null); + } // for + } // clearAllDrillDowns + + public void setOuterJoin(DataSourceType curTable, String joinType) { + String refDefinition = nvl(curTable.getRefDefinition()); + int outerJoinIdx = refDefinition.indexOf(" (+)"); + if (outerJoinIdx >= 0) + // Clear existing outer join + if (outerJoinIdx == (refDefinition.length() - 4)) + refDefinition = refDefinition.substring(0, outerJoinIdx); + else + refDefinition = refDefinition.substring(0, outerJoinIdx) + + refDefinition.substring(outerJoinIdx + 4); + + int equalSignIdx = refDefinition.indexOf("="); + if (equalSignIdx < 0) + // Ref. definition not present + return; + + if (refDefinition.indexOf(curTable.getTableId()) < equalSignIdx) { + // Cur. table is on the left side + if (nvl(joinType).equals(AppConstants.OJ_CURRENT)) + refDefinition = refDefinition.substring(0, equalSignIdx) + " (+)" + + refDefinition.substring(equalSignIdx); + else if (nvl(joinType).equals(AppConstants.OJ_JOINED)) + refDefinition = refDefinition + " (+)"; + } else { + // Joined table is on the left side + if (nvl(joinType).equals(AppConstants.OJ_CURRENT)) + refDefinition = refDefinition + " (+)"; + else if (nvl(joinType).equals(AppConstants.OJ_JOINED)) + refDefinition = refDefinition.substring(0, equalSignIdx) + " (+)" + + refDefinition.substring(equalSignIdx); + } + + curTable.setRefDefinition(refDefinition); + } // setOuterJoin + + public void addDataSourceType(ObjectFactory objFactory, String tableId, String tableName, + String tablePK, String displayName, String refTableId, String refDefinition, + String comment) throws RaptorException { + DataSourceType dst = objFactory.createDataSourceType(); + + dst.setTableId(tableId); + dst.setTableName(tableName); + dst.setTablePK(tablePK); + dst.setDisplayName(displayName); + if (nvl(refTableId).length() > 0) + dst.setRefTableId(refTableId); + if (nvl(refDefinition).length() > 0) + dst.setRefDefinition(refDefinition); + if (nvl(comment).length() > 0) + dst.setComment(comment); + + DataColumnList dataColumnList = objFactory.createDataColumnList(); + dst.setDataColumnList(dataColumnList); + + getDataSourceList().getDataSource().add(dst); + + resetCache(true); + } // addDataSourceType + + public void deleteDataSourceType(String tableId) { + super.deleteDataSourceType(tableId); + } // deleteDataSourceType + + public String getUniqueColumnId(String colName) { + String colId = ""; + + int colIdN = getAllColumns().size() + 1; + do { + colId = colName.substring(0, 2).toLowerCase() + (colIdN++); + } while (getColumnById(colId) != null); + + return colId; + } // getUniqueColumnId + + public DataColumnType addDataColumnType(ObjectFactory objFactory, String colId, + String tableId, // Table to which the new column belongs + String dbColName, String crossTabValue, String colName, String displayName, + int displayWidth, String displayAlignment, int orderSeq, boolean visible, + boolean calculated, String colType, String colFormat, boolean groupBreak, + int orderBySeq, String orderByAscDesc, String displayTotal, String colOnChart, + int chartSeq, String drillDownType, String drillDownURL, String drillDownParams, + String semaphoreId, String comment) throws RaptorException { + DataColumnType dct = null; + dct = objFactory.createDataColumnType(); + + dct.setColId(colId); + dct.setTableId(tableId); + dct.setDbColName(dbColName); + if (nvl(crossTabValue).length() > 0) + dct.setCrossTabValue(crossTabValue); + dct.setColName(colName); + dct.setDisplayName(displayName); + if (displayWidth > 0) + dct.setDisplayWidth(displayWidth); + if (nvl(displayAlignment).length() > 0) + dct.setDisplayAlignment(displayAlignment); + if (orderSeq > 0) + dct.setOrderSeq(orderSeq); + else + dct.setOrderSeq(getAllColumns().size() + 1); + dct.setVisible(visible); + dct.setCalculated(calculated); + // dct.setColType(colType); + if (nvl(colFormat).length() > 0) + dct.setColFormat(colFormat); + dct.setGroupBreak(groupBreak); + if (orderBySeq > 0) + dct.setOrderBySeq(orderBySeq); + if (nvl(orderByAscDesc).length() > 0) + dct.setOrderByAscDesc(orderByAscDesc); + if (nvl(displayTotal).length() > 0) + dct.setDisplayTotal(displayTotal); + if (nvl(colOnChart).length() > 0) + dct.setColOnChart(colOnChart); + if (chartSeq > 0) + dct.setChartSeq(chartSeq); + if (nvl(drillDownType).length() > 0) + dct.setDrillDownType(drillDownType); + if (nvl(drillDownURL).length() > 0) + dct.setDrillDownURL(drillDownURL); + if (nvl(drillDownParams).length() > 0) + dct.setDrillDownParams(drillDownParams); + if (nvl(semaphoreId).length() > 0) + dct.setSemaphoreId(semaphoreId); + if (nvl(comment).length() > 0) + dct.setComment(comment); + + dct.setDbColType(colType); + adjustColumnType(dct); + + // ColFilterList colFilterList = objFactory.createColFilterList(); + // dct.setColFilterList(colFilterList); + + getTableById(tableId).getDataColumnList().getDataColumn().add(dct); + + resetCache(false); + + return dct; + } // addDataColumnType + + public void deleteDataColumnType(String colId) { + int colOrder = getColumnById(colId).getOrderSeq(); + + List dcList = getColumnTableById(colId).getDataColumnList().getDataColumn(); + for (Iterator iterC = dcList.iterator(); iterC.hasNext();) { + DataColumnType dct = (DataColumnType) iterC.next(); + + if (dct.getColId().equals(colId) && dct.getOrderSeq() == colOrder) + iterC.remove(); + else if (dct.getOrderSeq() > colOrder) + dct.setOrderSeq(dct.getOrderSeq() - 1); + } // for + + if (getFormFieldList() != null) + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + if (nvl(fft.getColId()).equals(colId)) { + fft.setColId(""); + fft.setFieldType(FormField.FFT_TEXT); + if (nvl(fft.getDefaultValue()).equals(AppConstants.FILTER_MAX_VALUE) + || nvl(fft.getDefaultValue()) + .equals(AppConstants.FILTER_MIN_VALUE)) + fft.setDefaultValue(""); + } // if + } // for + + resetCache(false); + resetColumnOrderValues(); + } // deleteDataColumnType + + public void shiftColumnOrderUp(String colId) { + List reportCols = getAllColumns(); + for (int i = 0; i < reportCols.size(); i++) { + DataColumnType dct = (DataColumnType) reportCols.get(i); + + if (dct.getColId().equals(colId) && (i > 0)) { + DataColumnType dctUp = (DataColumnType) reportCols.get(i - 1); + dctUp.setOrderSeq(dctUp.getOrderSeq() + 1); + dct.setOrderSeq(dct.getOrderSeq() - 1); + break; + } // if + } // for + + Collections.sort(reportCols, new OrderSeqComparator()); + resetCache(true); + resetColumnOrderValues(); + } // shiftColumnOrderUp + + public void shiftColumnOrderDown(String colId) { + List reportCols = getAllColumns(); + for (int i = 0; i < reportCols.size(); i++) { + DataColumnType dct = (DataColumnType) reportCols.get(i); + + if (dct.getColId().equals(colId) && (i < reportCols.size() - 1)) { + DataColumnType dctDown = (DataColumnType) reportCols.get(i + 1); + dctDown.setOrderSeq(dctDown.getOrderSeq() - 1); + dct.setOrderSeq(dct.getOrderSeq() + 1); + break; + } // if + } // for + + Collections.sort(reportCols, new OrderSeqComparator()); + resetCache(true); + resetColumnOrderValues(); + } // shiftColumnOrderDown + + public void resetColumnOrderValues() { + List reportCols = getAllColumns(); + + int colOrder = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + dct.setOrderSeq(++colOrder); + } // for + + Collections.sort(reportCols, new OrderSeqComparator()); + } // resetColumnOrderValues + + public void addColFilterType(ObjectFactory objFactory, String colId, // Column + // to + // which + // the + // new + // filter + // belongs + String joinCondition, String openBrackets, String expression, String argType, + String argValue, String closeBrackets, String comment) throws RaptorException { + ColFilterType cft = objFactory.createColFilterType(); + + cft.setColId(colId); + cft.setJoinCondition(nvl(joinCondition, "AND")); + if (nvl(openBrackets).length() > 0) + cft.setOpenBrackets(openBrackets); + cft.setExpression(expression); + if (nvl(argType).length() > 0) + cft.setArgType(argType); + if (nvl(argValue).length() > 0) + cft.setArgValue(argValue); + if (nvl(closeBrackets).length() > 0) + cft.setCloseBrackets(closeBrackets); + if (nvl(comment).length() > 0) + cft.setComment(comment); + + DataColumnType dct = getColumnById(colId); + if (dct != null) { + if (dct.getColFilterList() == null) + dct.setColFilterList(objFactory.createColFilterList()); + + cft.setFilterSeq(dct.getColFilterList().getColFilter().size()); + dct.getColFilterList().getColFilter().add(cft); + } // if + + resetCache(true); + } // addColFilterType + + public void removeColumnFilter(String colId, int filterPos) { + DataColumnType dct = getColumnById(colId); + + if (dct.getColFilterList() != null) + try { + dct.getColFilterList().getColFilter().remove(filterPos); + } catch (IndexOutOfBoundsException e) { + } + + resetCache(true); + } // removeColumnFilter + + public void addColumnSort(String colId, String ascDesc) { + addColumnSort(colId, ascDesc, -1); + } // addColumnSort + + public void addColumnSort(String colId, String ascDesc, int sortOrder) { + if (sortOrder <= 0) { + sortOrder = 1; + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) + if (((DataColumnType) iter.next()).getOrderBySeq() > 0) + sortOrder++; + } // if + + DataColumnType dct = getColumnById(colId); + dct.setOrderBySeq(sortOrder); + dct.setOrderByAscDesc(ascDesc); + + resetCache(true); + } // addColumnSort + + public void removeColumnSort(String colId) { + DataColumnType dct = getColumnById(colId); + int sortOrder = dct.getOrderBySeq(); + + dct.setOrderBySeq(0); + dct.setOrderByAscDesc(null); + + if (sortOrder > 0) { + List reportCols = getAllColumns(); + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dct2 = (DataColumnType) iter.next(); + + if (dct2.getOrderBySeq() > sortOrder) + dct2.setOrderBySeq(dct2.getOrderBySeq() - 1); + } // for + } // if + + resetCache(true); + } // removeColumnSort + + public void shiftColumnSortUp(String colId) { + List reportCols = getAllColumns(); + Collections.sort(reportCols, new OrderBySeqComparator()); + + for (int i = 0; i < reportCols.size(); i++) { + DataColumnType dct = (DataColumnType) reportCols.get(i); + + if (dct.getColId().equals(colId) && (dct.getOrderBySeq() > 0)) { + DataColumnType dctUp = (DataColumnType) reportCols.get(i - 1); + if (dctUp.getOrderBySeq() > 0) + dctUp.setOrderBySeq(dctUp.getOrderBySeq() + 1); + dct.setOrderBySeq(dct.getOrderBySeq() - 1); + break; + } // if + } // for + + Collections.sort(reportCols, new OrderSeqComparator()); + resetCache(true); + } // shiftColumnSortUp + + public void shiftColumnSortDown(String colId) { + List reportCols = getAllColumns(); + Collections.sort(reportCols, new OrderBySeqComparator()); + + for (int i = 0; i < reportCols.size(); i++) { + DataColumnType dct = (DataColumnType) reportCols.get(i); + + if (dct.getColId().equals(colId) && (dct.getOrderBySeq() > 0)) { + DataColumnType dctDown = (DataColumnType) reportCols.get(i + 1); + if (dctDown.getOrderBySeq() > 0) + dctDown.setOrderBySeq(dctDown.getOrderBySeq() - 1); + dct.setOrderBySeq(dct.getOrderBySeq() + 1); + break; + } // if + } // for + + Collections.sort(reportCols, new OrderSeqComparator()); + resetCache(true); + } // shiftColumnSortDown + + /** ************************************************************************************************* */ + + public String generateNewSemaphoreId() { + if (getSemaphoreList() == null) + return "sem1"; + + String semaphoreId = null; + boolean idExists = true; + for (int i = 1; idExists; i++) { + semaphoreId = "sem" + i; + idExists = false; + for (Iterator iter = getSemaphoreList().getSemaphore().iterator(); iter.hasNext();) + if (semaphoreId.equals(((SemaphoreType) iter.next()).getSemaphoreId())) { + idExists = true; + break; + } + } // for + + return semaphoreId; + } // generateNewSemaphoreId + + public SemaphoreType addSemaphore(ObjectFactory objFactory, SemaphoreType semaphoreType) + throws RaptorException { + SemaphoreType sem = null; + try { + if (getSemaphoreList() == null) + setSemaphoreList(objFactory.createSemaphoreList()); + + String semaphoreName = null; + boolean nameExists = true; + for (int i = 1; nameExists; i++) { + semaphoreName = semaphoreType.getSemaphoreName() + ((i > 1) ? (" v" + i) : ""); + nameExists = false; + for (Iterator iter2 = getSemaphoreList().getSemaphore().iterator(); iter2 + .hasNext();) + if (semaphoreName.equals(((SemaphoreType) iter2.next()).getSemaphoreName())) { + nameExists = true; + break; + } + } // for + + sem = cloneSemaphoreType(objFactory, semaphoreType); + getSemaphoreList().getSemaphore().add(sem); + + sem.setSemaphoreId(generateNewSemaphoreId()); + sem.setSemaphoreName(semaphoreName); + } catch (JAXBException ex) { + throw new RaptorException(ex.getMessage(), ex.getCause()); + } + + return sem; + } // addSemaphore + + public SemaphoreType addSemaphoreType(ObjectFactory objFactory, String semaphoreName, + String semaphoreType, String comment) throws RaptorException { + SemaphoreType sem = null; + if (getSemaphoreList() == null) + setSemaphoreList(objFactory.createSemaphoreList()); + + sem = objFactory.createSemaphoreType(); + getSemaphoreList().getSemaphore().add(sem); + + sem.setSemaphoreId(generateNewSemaphoreId()); + sem.setSemaphoreName(semaphoreName); + sem.setSemaphoreType(nvl(semaphoreType)); + if (nvl(comment).length() > 0) + sem.setComment(comment); + + FormatList formatList = objFactory.createFormatList(); + sem.setFormatList(formatList); + return sem; + } // addSemaphoreType + + + public String getNextIdForJavaScriptElement (ObjectFactory objFactory, String fieldId) throws RaptorException { + String id = ""; + JavascriptItemType jit = null; + int incr = 0; + if (getJavascriptList() == null) { + setJavascriptList(objFactory.createJavascriptList()); + return fieldId + "|1"; + } else { + if(getJavascriptList().getJavascriptItem().iterator().hasNext()) { + for (Iterator iter = getJavascriptList().getJavascriptItem().iterator(); iter.hasNext();) { + jit = (JavascriptItemType) iter.next(); + logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^JAVASCRIPTITEMTYPE " + jit.getFieldId() + " " + fieldId + " " + id)); + if(nvl(jit.getFieldId()).length()>0 && jit.getFieldId().equals(fieldId)) { + ++incr; + } + } // for + return fieldId + "|"+incr; + } else { + return fieldId + "|1"; + } + + } + //return null; + } + + public JavascriptItemType addJavascriptType(ObjectFactory objFactory, String id) throws RaptorException { + JavascriptItemType javascriptItemType = null; + int flag = 0; // checking whether id existing in the list + if (getJavascriptList() == null) { + setJavascriptList(objFactory.createJavascriptList()); + javascriptItemType = objFactory.createJavascriptItemType(); + getJavascriptList().getJavascriptItem().add(javascriptItemType); + return javascriptItemType; + } else { + + for (Iterator iter = getJavascriptList().getJavascriptItem().iterator(); iter.hasNext();) { + javascriptItemType = (JavascriptItemType)iter.next(); + if(javascriptItemType.getId().equals(id) && !id.startsWith("-1")) { + flag = 1; + break; + } + } + if(flag == 1) return javascriptItemType; + else { + javascriptItemType = objFactory.createJavascriptItemType(); + getJavascriptList().getJavascriptItem().add(javascriptItemType); + return javascriptItemType; + } + } + + } // addSemaphoreType + + public boolean deleteJavascriptType(String id) throws RaptorException { + JavascriptItemType javascriptType = null; + if (getJavascriptList() == null) + return true; + for (Iterator iter = getJavascriptList().getJavascriptItem().iterator(); iter.hasNext();) { + javascriptType = (JavascriptItemType)iter.next(); + if(javascriptType.getId().equals(id)) { + iter.remove(); + return true; + } + } + return false; + } // addSemaphoreType + + public static FormatType addEmptyFormatType(ObjectFactory objFactory, + SemaphoreType semaphore) throws RaptorException { + FormatType fmt = null; + fmt = objFactory.createFormatType(); + semaphore.getFormatList().getFormat().add(fmt); + + String formatId = null; + boolean idExists = true; + for (int i = 1; idExists; i++) { + formatId = semaphore.getSemaphoreId() + "_fmt" + i; + idExists = false; + for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter + .hasNext();) + if (formatId.equals(((FormatType) iter.next()).getFormatId())) { + idExists = true; + break; + } + } // for + fmt.setFormatId(formatId); + return fmt; + } // addEmptyFormatType + + public static void deleteFormatType(SemaphoreType semaphore, String formatId) { + for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter.hasNext();) + if (formatId.equals(((FormatType) iter.next()).getFormatId())) { + iter.remove(); + break; + } // if + } // deleteFormatType + + public FormFieldType addFormFieldType(ObjectFactory objFactory, String fieldName, + String colId, String fieldType, String validationType, String mandatory, + String defaultValue, String fieldSQL, String comment, Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL) throws RaptorException { + FormFieldType fft = null; + fft = objFactory.createFormFieldType(); + + fft.setFieldName(fieldName); + fft.setColId(colId); + fft.setFieldType(fieldType); + fft.setValidationType(validationType); + fft.setMandatory(nvl(mandatory, "N")); + fft.setDefaultValue(nvl(defaultValue)); + fft.setOrderBySeq((getFormFieldList() == null) ? 1 : getFormFieldList().getFormField() + .size() + 1); + fft.setFieldSQL(fieldSQL); + //fft.setRangeStartDate(rangeStartDate); + //fft.setRangeEndDate(rangeEndDate); + + try { + fft.setRangeStartDate(DatatypeFactory.newInstance() + .newXMLGregorianCalendar(rangeStartDate.YEAR, rangeStartDate.MONTH, rangeStartDate.DAY_OF_WEEK, rangeStartDate.HOUR, rangeStartDate.MINUTE, rangeStartDate.SECOND, rangeStartDate.MILLISECOND, rangeStartDate.ZONE_OFFSET)); + fft.setRangeStartDate(DatatypeFactory.newInstance() + .newXMLGregorianCalendar(rangeEndDate.YEAR, rangeEndDate.MONTH, rangeEndDate.DAY_OF_WEEK, rangeEndDate.HOUR, rangeEndDate.MINUTE, rangeEndDate.SECOND, rangeEndDate.MILLISECOND, rangeEndDate.ZONE_OFFSET)); + /*currField.setRangeEndDate(DatatypeFactory.newInstance() + .newXMLGregorianCalendar(end));*/ + } catch (DatatypeConfigurationException ex) { + + } + + fft.setRangeStartDateSQL(rangeStartDateSQL); + fft.setRangeEndDateSQL(rangeEndDateSQL); + if (nvl(comment).length() > 0) + fft.setComment(comment); + + String fieldId = null; + boolean idExists = true; + for (int i = 1; idExists; i++) { + fieldId = "ff" + i; + idExists = false; + if (getFormFieldList() != null) + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter + .hasNext();) + if (fieldId.equals(((FormFieldType) iter.next()).getFieldId())) { + idExists = true; + break; + } + } // for + fft.setFieldId(fieldId); + + if (getFormFieldList() == null) { + FormFieldList formFieldList = objFactory.createFormFieldList(); + setFormFieldList(formFieldList); + } + + getFormFieldList().getFormField().add(fft); + return fft; + } // addFormFieldType + + //addCustomizedTextForParameters + public void addCustomizedTextForParameters(String comment) throws RaptorException { + getFormFieldList().setComment(comment); + } + + public FormFieldType addFormFieldBlank(ObjectFactory objFactory) throws RaptorException { + FormFieldType fft = null; + fft = objFactory.createFormFieldType(); + + fft.setFieldName("BLANK"); + fft.setColId("bk"); + fft.setFieldType(FormField.FFT_BLANK); + fft.setOrderBySeq((getFormFieldList() == null) ? 1 : getFormFieldList().getFormField() + .size() + 1); + String fieldId = null; + boolean idExists = true; + for (int i = 1; idExists; i++) { + fieldId = "ff" + i; + idExists = false; + if (getFormFieldList() != null) + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter + .hasNext();) + if (fieldId.equals(((FormFieldType) iter.next()).getFieldId())) { + idExists = true; + break; + } + } // for + fft.setFieldId(fieldId); + + if (getFormFieldList() == null) { + FormFieldList formFieldList = objFactory.createFormFieldList(); + setFormFieldList(formFieldList); + } + + getFormFieldList().getFormField().add(fft); + return fft; + } // addFormFieldBlank + + public void replaceFormFieldReferences(String fieldName, String replaceWith) { + if (fieldName.equals(replaceWith)) + return; + + for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + + if (dct.isCalculated() && dct.getColName().indexOf(fieldName) >= 0) + dct.setColName(Utils.replaceInString(dct.getColName(), fieldName, nvl( + replaceWith, "NULL"))); + + if (dct.getColFilterList() != null) + for (Iterator iter2 = dct.getColFilterList().getColFilter().iterator(); iter2 + .hasNext();) { + ColFilterType cft = (ColFilterType) iter2.next(); + + if (nvl(cft.getArgType()).equals(AppConstants.AT_FORM) + && nvl(cft.getArgValue()).equals(fieldName)) + cft.setArgValue(replaceWith); + } // for + } // for + } // replaceFormFieldReferences + + public void deleteFormField(String fieldId) { + String fieldDisplayName = null; + + int orderBySeq = Integer.MAX_VALUE; + if (getFormFieldList() != null) + for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + + if (fieldId.equals(fft.getFieldId())) { + //orderBySeq = fft.getOrderBySeq(); + fieldDisplayName = getFormFieldDisplayName(fft); + iter.remove(); + } else if (fft.getOrderBySeq()!=null && (fft.getOrderBySeq().intValue() > orderBySeq)) + fft.setOrderBySeq(fft.getOrderBySeq() - 1); + } // for + + if (fieldDisplayName != null) + replaceFormFieldReferences(fieldDisplayName, ""); + } // deleteFormField + + public void shiftFormFieldUp(String fieldId) { + if (getFormFieldList() == null) + return; + + for (int i = 0; i < getFormFieldList().getFormField().size(); i++) { + FormFieldType fft = (FormFieldType) getFormFieldList().getFormField().get(i); + + if (fft.getFieldId().equals(fieldId) && (i > 0)) { + FormFieldType prevFft = (FormFieldType) getFormFieldList().getFormField().get( + i - 1); + prevFft.setOrderBySeq(prevFft.getOrderBySeq() + 1); + fft.setOrderBySeq((fft.getOrderBySeq() == null)?0:fft.getOrderBySeq() - 1); + + getFormFieldList().getFormField().remove(i); + getFormFieldList().getFormField().add(i - 1, fft); + return; + } // if + } // for + } // shiftFormFieldUp + + public void shiftFormFieldDown(String fieldId) { + if (getFormFieldList() == null) + return; + + for (int i = 0; i < getFormFieldList().getFormField().size(); i++) { + FormFieldType fft = (FormFieldType) getFormFieldList().getFormField().get(i); + + if (fft.getFieldId().equals(fieldId) + && (i < getFormFieldList().getFormField().size() - 1)) { + FormFieldType nextFft = (FormFieldType) getFormFieldList().getFormField().get( + i + 1); + nextFft.setOrderBySeq((nextFft.getOrderBySeq() == null)?0:nextFft.getOrderBySeq() - 1); + fft.setOrderBySeq((fft.getOrderBySeq() == null)?0:fft.getOrderBySeq() + 1); + + getFormFieldList().getFormField().remove(i + 1); + getFormFieldList().getFormField().add(i, nextFft); + return; + } // if + } // for + } // shiftFormFieldDown + + public static void addFormFieldPredefinedValue(ObjectFactory objFactory, + FormFieldType formField, String predefinedValue) throws RaptorException { + if (formField.getPredefinedValueList() == null) { + PredefinedValueList predefinedValueList = objFactory.createPredefinedValueList(); + formField.setPredefinedValueList(predefinedValueList); + } // if + + if (predefinedValue.length() > 0) { + formField.getPredefinedValueList().getPredefinedValue().add(predefinedValue); + Collections.sort(formField.getPredefinedValueList().getPredefinedValue()); + } // if + } // addFormFieldPredefinedValue + + public static void deleteFormFieldPredefinedValue(FormFieldType formField, + String predefinedValue) { + if (formField != null && formField.getPredefinedValueList() != null + && predefinedValue.length() > 0) + for (Iterator iter = formField.getPredefinedValueList().getPredefinedValue() + .iterator(); iter.hasNext();) + if (predefinedValue.equals((String) iter.next())) { + iter.remove(); + break; + } // if + } // deleteFormFieldPredefinedValue + + /** ************************************************************************************************* */ + + private int curSQLParsePos = 0; + + private String getNextSQLParseToken(String sql, boolean updateParsePos) { + int braketCount = 0; + boolean isInsideQuote = false; + StringBuffer nextToken = new StringBuffer(); + for (int idxNext = curSQLParsePos; idxNext < sql.length(); idxNext++) { + char ch = sql.charAt(idxNext); + + if (Character.isWhitespace(ch) || ch == ',') { + if (ch == ',') + nextToken.append(ch); + + if (nextToken.length() == 0) + continue; + else if (braketCount == 0 && (!isInsideQuote)) { + if (updateParsePos) + curSQLParsePos = idxNext + ((ch == ',') ? 1 : 0); + break; + } else if (ch != ',' && nextToken.charAt(nextToken.length() - 1) != ' ') + nextToken.append(' '); + } else { + nextToken.append(ch); + + if (ch == '(' || ch == '[') + braketCount++; + else if (ch == ')' || ch == ']') + braketCount--; + else if (ch == '\''/* ||ch=='\"' */) + isInsideQuote = (!isInsideQuote); + } // else + } // for + + return nextToken.toString(); + } // getNextSQLParseToken + + private boolean isParseSQLColID(String token) { + if (nvl(token).length() == 0) + return false; + + for (int i = 0; i < token.length(); i++) { + char ch = token.charAt(i); + + if (i == 0 && ch == '_') + return false; + + if (!(Character.isLetterOrDigit(ch) || ch == '_')) + return false; + } // for + + return true; + } // isParseSQLColID + + private DataColumnType getParseSQLDataColumn(String sqlExpression, String colId, + StringBuffer parsedSQL, Vector updatedReportCols, boolean isCYMBALScript) throws RaptorException { + DataColumnType dct = null; + + if (colId != null) { + if (!isParseSQLColID(colId)) + throw new org.openecomp.portalsdk.analytics.error.ValidationException( + "[" + + colId + + "] must either be a valid column id consisting only of letters, numbers, and underscores, or there must be a comma in front of it."); + + dct = getColumnById(colId); + } else { + // Getting unique column id + colId = ""; + int colIdN = 0; + for (int i = 0; (i < sqlExpression.length()) && (colIdN < 2); i++) + if (Character.isLetter(sqlExpression.charAt(i))) { + colId += sqlExpression.toLowerCase().charAt(i); + colIdN++; + } // if + + colIdN = getAllColumns().size() + updatedReportCols.size(); + for (boolean idAlreadyUsed = true; idAlreadyUsed; colIdN++) { + String newColId = colId + colIdN; + idAlreadyUsed = false; + + for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) + if (newColId.equals(((DataColumnType) iter.next()).getColId())) { + idAlreadyUsed = true; + break; + } + + if (!idAlreadyUsed) + for (Iterator iter = updatedReportCols.iterator(); iter.hasNext();) + if (newColId.equals(((DataColumnType) iter.next()).getColId())) { + idAlreadyUsed = true; + break; + } + } // for + + colId += (colIdN - 1); + } // else + + if (dct == null) { + dct = (new ObjectFactory()).createDataColumnType(); + dct.setColId(colId); + dct.setDisplayWidth(10); + dct.setDisplayAlignment("Left"); + dct.setVisible(true); + dct.setGroupBreak(false); // ??? + if(!isCYMBALScript) { + boolean isValidIdentifier = Character.isLetterOrDigit(sqlExpression.charAt(0)); + for (int i = 0; i < sqlExpression.length(); i++) + if (!(Character.isLetterOrDigit(sqlExpression.charAt(i)) + || (sqlExpression.charAt(i) == '_') || (sqlExpression.charAt(i) == '$'))) { + isValidIdentifier = false; + break; + } // if + + if (isValidIdentifier) { + dct.setDisplayName(sqlExpression); + } else { + dct.setDisplayName(colId); + } // else + } else dct.setDisplayName(colId); + } // if + if(!isCYMBALScript) + sqlExpression = sqlExpression.replaceAll(", '", ",'"); + dct.setDbColName(sqlExpression); + dct.setColName(sqlExpression); + dct.setCalculated(true); + dct.setColType(AppConstants.CT_CHAR); + dct.setDbColType(AppConstants.CT_CHAR); + adjustColumnType(dct); // ??? + if(!isCYMBALScript) { + if (parsedSQL.toString().equals("SELECT ") + || parsedSQL.toString().equals("SELECT DISTINCT ")) + parsedSQL.append("\n\t"); + else + parsedSQL.append(", \n\t"); + parsedSQL.append(sqlExpression); + parsedSQL.append(" "); + parsedSQL.append(colId); + } + + return dct; + } // getParseSQLDataColumn + + public void parseReportSQL(String sql) throws RaptorException { + StringBuffer parsedSQL = new StringBuffer(); + + Vector updatedReportCols = new Vector(); + + curSQLParsePos = 0; + int lastParsePos = curSQLParsePos; + String lastToken = null; + String nextToken = getNextSQLParseToken(sql, true); + + String dbInfo = getDBInfo(); + boolean isCYMBALScript = false; + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + String dbType = remDbInfo.getDBType(dbInfo); + if (dbType.equals("DAYTONA") && !(nextToken.toUpperCase().equals("SELECT"))) { + isCYMBALScript = true; + } + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + if ( isCYMBALScript == false ) { + while (nextToken.length() > 0) { + if (parsedSQL.length() == 0) { + if (nextToken.toUpperCase().equals("SELECT")) + parsedSQL.append("SELECT "); + else + throw new org.openecomp.portalsdk.analytics.error.ValidationException( + "The SQL must start with the SELECT keyword."); + } else if (nextToken.toUpperCase().equals("DISTINCT") + && parsedSQL.toString().equals("SELECT ")) { + parsedSQL.append("DISTINCT "); + } else if (nextToken.equals("*") + && (parsedSQL.toString().equals("SELECT ") || parsedSQL.toString().equals( + "SELECT DISTINCT "))) { + throw new org.openecomp.portalsdk.analytics.error.ValidationException( + "You cannot use \"SELECT *\". Please specify select columns/expressions."); + } else if (nextToken.toUpperCase().equals("FROM")) { + if (lastToken != null) { + updatedReportCols.add(getParseSQLDataColumn(lastToken, null, parsedSQL, + updatedReportCols, false)); + lastToken = null; + } + + parsedSQL.append(" \n"); + while (lastParsePos < sql.length() + && Character.isWhitespace(sql.charAt(lastParsePos))) + lastParsePos++; + parsedSQL.append(sql.substring(lastParsePos)); + break; + } else { + if (nextToken.charAt(nextToken.length() - 1) == ',') { + // The token ends with , + nextToken = nextToken.substring(0, nextToken.length() - 1); + + if (nextToken.length() == 0) { + if (lastToken != null) { + updatedReportCols.add(getParseSQLDataColumn(lastToken, null, + parsedSQL, updatedReportCols, false)); + lastToken = null; + } // else just comma => ignore it + } else { + if (lastToken != null) { + updatedReportCols.add(getParseSQLDataColumn(lastToken, nextToken, + parsedSQL, updatedReportCols, false)); + lastToken = null; + } else + updatedReportCols.add(getParseSQLDataColumn(nextToken, null, + parsedSQL, updatedReportCols, false)); + } + } else { + // The token doesn't end with , + if (lastToken == null) + lastToken = nextToken; + else { + String token = getNextSQLParseToken(sql, false); + if (!token.toUpperCase().equals("FROM")) + throw new org.openecomp.portalsdk.analytics.error.ValidationException( + "|FROM keyword or a comma expected after [" + nextToken + + "]."); + + updatedReportCols.add(getParseSQLDataColumn(lastToken, nextToken, + parsedSQL, updatedReportCols, false)); + lastToken = null; + } // else + } // else + } // else + + lastParsePos = curSQLParsePos; + nextToken = getNextSQLParseToken(sql, true); + } // while + } else { // if CYMBAL Script + curSQLParsePos = 0; + Pattern re = null; + Matcher matcher = null; + String extracted = null; + nextToken = getNextCYMBALSQLParseToken(sql,true); + while (nextToken.length() > 0) { + if (lastToken == null) lastToken = nextToken; + + if( lastToken.toUpperCase().startsWith("DO DISPLAY")) { + re = Pattern.compile("each(.*)\\[.(.*?)\\]"); //\\[(.*?)\\] + matcher = re.matcher(nextToken); + if (matcher.find()) { + extracted = matcher.group(); + re = Pattern.compile("\\[(.*?)\\]"); + matcher = re.matcher(nextToken); + if(matcher.find()) { + extracted = matcher.group(); + extracted = extracted.substring(1,extracted.length()-1); + StringTokenizer sToken = new StringTokenizer(extracted, ","); + while(sToken.hasMoreTokens()) { + String str1 = sToken.nextToken().trim().substring(1); + updatedReportCols.add(getParseSQLDataColumn("", str1, + new StringBuffer(""), updatedReportCols, true)); + } + } + + } + + } + lastToken = nextToken; + nextToken = getNextCYMBALSQLParseToken(sql, true); + } + + } + if (updatedReportCols.size() == 0) + throw new org.openecomp.portalsdk.analytics.error.ValidationException( + "The SQL statement must have at least one column in the SELECT clause."); + if (getDataSourceList().getDataSource().size() == 0) + addDataSourceType(new ObjectFactory(), "du0", "DUAL", "", "DUAL", null, null, null); + DataSourceType dst = (DataSourceType) getDataSourceList().getDataSource().get(0); + dst.getDataColumnList().getDataColumn().clear(); + + for (int i = 0; i < updatedReportCols.size(); i++) { + DataColumnType dct = (DataColumnType) updatedReportCols.get(i); + dct.setTableId(dst.getTableId()); + dct.setOrderSeq(i + 1); + dst.getDataColumnList().getDataColumn().add(dct); + } // for + setReportSQL(parsedSQL.toString()); + resetCache(false); + } // parseReportSQL + + private String getNextCYMBALSQLParseToken(String sql, boolean updateParsePos) { + int braketCount = 0; + boolean isInsideQuote = false; + StringBuffer nextToken = new StringBuffer(); + for (int idxNext = curSQLParsePos; idxNext < sql.length(); idxNext++) { + char ch = sql.charAt(idxNext); + + if (ch!='\n') { + nextToken.append(ch); + if (updateParsePos) + curSQLParsePos = idxNext; + } + else { + curSQLParsePos = idxNext+1; + break; + } + } // for + + return nextToken.toString(); + } // getNextSQLParseToken + + public void addChartAdditionalOptions(ObjectFactory objFactory) throws RaptorException { + ChartAdditionalOptions chartOptions = objFactory.createChartAdditionalOptions(); + cr.setChartAdditionalOptions(chartOptions); + } + + public void addChartDrillOptions(ObjectFactory objFactory) throws RaptorException { + ChartDrillOptions chartOptions = objFactory.createChartDrillOptions(); + cr.setChartDrillOptions(chartOptions); +} + + public void addDataminingOptions(ObjectFactory objFactory) throws RaptorException { + DataminingOptions dataminingOptions = objFactory.createDataminingOptions(); + cr.setDataminingOptions(dataminingOptions); + } + /*public void addChartAdditionalOptions(ObjectFactory objFactory, String chartType, String chartMultiplePieOrder, String chartMultiplePieLabelDisplay, + String chartOrientation, String secondaryChartRenderer, String chartDisplay, String legendPosition, + String labelAngle) throws RaptorException { + try { + ChartAdditionalOptions chartOptions = objFactory.createChartAdditionalOptions(); + + if (nvl(chartMultiplePieOrder).length() > 0) + chartOptions.setChartMultiplePieOrder(chartMultiplePieOrder); + if (nvl(chartMultiplePieLabelDisplay).length() > 0) + chartOptions.setChartMultiplePieLabelDisplay(chartMultiplePieLabelDisplay); + if (nvl(chartOrientation).length() > 0) + chartOptions.setChartOrientation(chartOrientation); + if (nvl(secondaryChartRenderer).length() > 0) + chartOptions.setSecondaryChartRenderer(secondaryChartRenderer); + if (nvl(chartDisplay).length() > 0) + chartOptions.setChartDisplay(chartDisplay); + if (nvl(legendPosition).length() > 0) + chartOptions.setLegendPosition(legendPosition); + if (nvl(labelAngle).length() > 0) + chartOptions.setLabelAngle(labelAngle); + + cr.setChartAdditionalOptions(chartOptions); + } catch (JAXBException ex) { + throw new RaptorException(ex.getMessage(), ex.getCause()); + } + } // addChartAdditionalOptions*/ + + +} // ReportDefinition diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportLogEntry.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportLogEntry.java new file mode 100644 index 00000000..db69e9d8 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportLogEntry.java @@ -0,0 +1,89 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.RaptorObject; + +public class ReportLogEntry extends RaptorObject { + private String logTime = null; + + private String userName = null; + + private String action = null; + + private String timeTaken; + + private String runIcon; + + public ReportLogEntry() { + super(); + } + + public ReportLogEntry(String logTime, String userName, String action, String timeTaken, String runIcon) { + this(); + + setLogTime(logTime); + setUserName(userName); + setAction(action); + setTimeTaken(timeTaken); + setRunIcon(runIcon); + } // ReportLogEntry + + public String getLogTime() { + return logTime; + } + + public String getUserName() { + return userName; + } + + public String getAction() { + return action; + } + + public void setLogTime(String logTime) { + this.logTime = logTime; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public void setAction(String action) { + this.action = action; + } + + public String getTimeTaken() { + return timeTaken; + } + + public void setTimeTaken(String timeTaken) { + this.timeTaken = timeTaken; + } + + public String getRunIcon() { + return runIcon; + } + + public void setRunIcon(String runIcon) { + this.runIcon = runIcon; + } + +} // ReportLogEntry diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportMap.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportMap.java new file mode 100644 index 00000000..e3c417a1 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportMap.java @@ -0,0 +1,86 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.openecomp.portalsdk.analytics.RaptorObject; +import org.openecomp.portalsdk.analytics.view.DataRow; +import org.openecomp.portalsdk.analytics.view.DataValue; +import org.openecomp.portalsdk.analytics.view.ReportData; + +public class ReportMap extends RaptorObject { + String markerColor = ""; + String addressColumn = ""; + String dataColumn = ""; + String isMapAllowedYN = ""; + String addAddressInDataYN = ""; + List markers = new ArrayList(); + + public String getIsMapAllowedYN() { + return isMapAllowedYN; + } + public void setIsMapAllowedYN(String isMapAllowedYN) { + this.isMapAllowedYN = isMapAllowedYN; + } + public ReportMap(String markerColor, String addressColumn, String dataColumn, String isMapAllowed, String addAddressInDataYN){ + this.setMarkerColor(markerColor); + this.setAddressColumn(addressColumn); + this.setDataColumn(dataColumn); + this.setIsMapAllowedYN(isMapAllowed); + this.setAddAddressInDataYN(addAddressInDataYN); + } + public String getAddressColumn() { + return addressColumn; + } + public void setAddressColumn(String addressColumn) { + this.addressColumn = addressColumn; + } + public String getDataColumn() { + return dataColumn; + } + public void setDataColumn(String dataColumn) { + this.dataColumn = dataColumn; + } + public String getMarkerColor() { + return markerColor; + } + public void setMarkerColor(String markerColor) { + this.markerColor = markerColor; + } + public List getMarkers() { + return markers; + } + public void setMarkers(List markers) { + this.markers = markers; + } + public String getAddAddressInDataYN() { + return addAddressInDataYN; + } + public void setAddAddressInDataYN(String addAddressInDataYN) { + this.addAddressInDataYN = addAddressInDataYN; + } + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportSchedule.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportSchedule.java new file mode 100644 index 00000000..d95c91b5 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/ReportSchedule.java @@ -0,0 +1,1407 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.Writer; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.analytics.RaptorObject; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException; +import org.openecomp.portalsdk.analytics.error.ReportSQLException; +import org.openecomp.portalsdk.analytics.error.UserDefinedException; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.model.base.NameComparator; +import org.openecomp.portalsdk.analytics.model.runtime.FormField; +import org.openecomp.portalsdk.analytics.model.runtime.ReportParamValues; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.system.DbUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class ReportSchedule extends RaptorObject { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportSchedule.class); + + + private String reportID = null; + + private String scheduleUserID = null; + + private String scheduleID = ""; + + private boolean infoUpdated = false; + + private String schedEnabled = "Y"; + + private String startDate = ""; + + private String endDate = ""; + + private String runDate = ""; + + private String runHour = "12"; + + private String runMin = "00"; + + private String runAMPM = "AM"; + + private String endHour = "11"; + + private String endMin = "45"; + + private String endAMPM = "PM"; + + private String recurrence = ""; + + private String conditional = "N"; + + private String conditionSQL = ""; + + private String notify_type = "1"; //1 -- link, 2 -- pdf, 4 -- excel, 3 -- csv + + private String encryptMode = "N"; //1 -- link, 2 -- pdf, 4 -- excel, 3 -- csv + + private String attachment = "Y"; //1 -- link, 2 -- pdf, 4 -- excel, 3 -- csv + + private String downloadLimit = "0"; + + private String formFields = ""; + + private Vector emailToUsers = new Vector(); + + private Vector emailToRoles = new Vector(); + + public ReportSchedule(String reportID, String scheduleUserID, boolean loadData, HttpServletRequest request) { + super(); + + setReportID(reportID); + setScheduleUserID(scheduleUserID); + if(loadData) + loadScheduleData(request); + else + newScheduleData(); + } // ReportSchedule + + public ReportSchedule(String reportID, String scheduleID, String scheduleUserID, HttpServletRequest request) { + super(); + + setReportID(reportID); + setScheduleID(scheduleID); + setScheduleUserID(scheduleUserID); + loadScheduleData(request); + } // ReportSchedule + + void setReportID(String reportID) { + this.reportID = reportID; + } + + public String getSchedEnabled() { + return schedEnabled; + } + + public String getStartDate() { + return startDate; + } + + public String getEndDate() { + return endDate; + } + + public String getRunDate() { + return runDate; + } + + public String getRunHour() { + return runHour; + } + + public String getRunMin() { + return runMin; + } + + public String getRunAMPM() { + return runAMPM; + } + + public String getRecurrence() { + return recurrence; + } + + public String getConditional() { + return conditional; + } + + public String getConditionSQL() { + return conditionSQL; + } + + public List getEmailToUsers() { + return emailToUsers; + } + + public List getEmailToRoles() { + return emailToRoles; + } + + /** + * @return the downloadLimit + */ + public String getDownloadLimit() { + return downloadLimit; + } + + /** + * @param downloadLimit the downloadLimit to set + */ + public void setDownloadLimit(String downloadLimit) { + if(nvl(downloadLimit).equals(this.downloadLimit)) + return; + this.downloadLimit = nvl(downloadLimit,"0"); + infoUpdated = true; + } + + /** + * @return the formFields + */ + public String getFormFields() { + return formFields; + } + + /** + * @param formFields the formFields to set + */ + public void setFormFields(String formFields) { + if(nvl(formFields).equals(this.formFields)) + return; + this.formFields = nvl(formFields); + infoUpdated = true; + } + + public String getNotify_type() { + return notify_type; + } + + /** + * @param notify_type the notify_type to set + * 1 -- link (default), 2 -- pdf, 4 -- excel + */ + public void setNotify_type(String notify_type) { + if(nvl(notify_type).equals(this.notify_type)) + return; + this.notify_type = nvl(notify_type,"1"); + infoUpdated = true; + } + + public void setSchedEnabled(String schedEnabled) { + if (nvl(schedEnabled).equals(this.schedEnabled)) + return; + infoUpdated = true; + this.schedEnabled = nvl(schedEnabled, "N"); + } + + public void setStartDate(String startDate) { + if (nvl(startDate).equals(this.startDate)) + return; + infoUpdated = true; + this.startDate = nvl(startDate); + } + + public void setEndDate(String endDate) { + if (nvl(endDate).equals(this.endDate)) + return; + infoUpdated = true; + this.endDate = nvl(endDate); + } + + public void setRunDate(String runDate) { + if (nvl(runDate).equals(this.runDate)) + return; + infoUpdated = true; + this.runDate = nvl(runDate); + } + + public void setRunHour(String runHour) { + if (nvl(runHour).equals(this.runHour)) + return; + infoUpdated = true; + this.runHour = nvl(runHour, "12"); + } + + public void setRunMin(String runMin) { + if (nvl(runMin).equals(this.runMin)) + return; + infoUpdated = true; + this.runMin = nvl(runMin, "00"); + } + + public void setRunAMPM(String runAMPM) { + if (nvl(runAMPM).equals(this.runAMPM)) + return; + infoUpdated = true; + this.runAMPM = nvl(runAMPM, "AM"); + } + + public void setRecurrence(String recurrence) { + if (nvl(recurrence).equals(this.recurrence)) + return; + infoUpdated = true; + this.recurrence = nvl(recurrence); + } + + public void setConditional(String conditional) { + if (nvl(conditional).equals(this.conditional)) + return; + infoUpdated = true; + this.conditional = nvl(conditional, "N"); + } + + public void setConditionSQL(String conditionSQL) { + if (nvl(conditionSQL).equals(this.conditionSQL)) + return; + infoUpdated = true; + this.conditionSQL = nvl(conditionSQL); + } + + public void addEmailToUser(String userId, String userName) { + if (nvl(userId).length() == 0) + return; + + for (int i = 0; i < emailToUsers.size(); i++) { + IdNameValue selUser = (IdNameValue) emailToUsers.get(i); + if (userId.equals(selUser.getId())) + return; + } // for + + emailToUsers.add(new IdNameValue(userId, userName)); + Collections.sort(emailToUsers, new NameComparator()); + infoUpdated = true; + } // addEmailToUser + + + public void addEmailArrayToUser(ArrayList allSelectedUsers) { + if (allSelectedUsers==null || allSelectedUsers.size()<=0) + return; + emailToUsers.removeAllElements(); + for (int i = 0; i < allSelectedUsers.size(); i++) { + emailToUsers.add(allSelectedUsers.get(i)); + } + Collections.sort(emailToUsers, new NameComparator()); + infoUpdated = true; + } // addEmailArrayToUser + + public void removeEmailToUser(String userId) { + if (nvl(userId).length() == 0) + return; + + for (int i = 0; i < emailToUsers.size(); i++) { + IdNameValue selUser = (IdNameValue) emailToUsers.get(i); + if (userId.equals(selUser.getId())) { + infoUpdated = true; + emailToUsers.remove(i); + return; + } // if + } // for + } // removeEmailToUser + + public void addEmailToRole(String roleId, String roleName) { + if (nvl(roleId).length() == 0) + return; + + for (int i = 0; i < emailToRoles.size(); i++) { + IdNameValue selRole = (IdNameValue) emailToRoles.get(i); + if (roleId.equals(selRole.getId())) + return; + } // for + + emailToRoles.add(new IdNameValue(roleId, roleName)); + Collections.sort(emailToRoles, new NameComparator()); + infoUpdated = true; + } // addEmailToRole + + public void addEmailArrayToRole(ArrayList allSelectedRoles) { + if (allSelectedRoles==null || allSelectedRoles.size()<=0) + return; + emailToRoles.removeAllElements(); + for (int i = 0; i < allSelectedRoles.size(); i++) { + emailToRoles.add(allSelectedRoles.get(i)); + } + Collections.sort(emailToRoles, new NameComparator()); + infoUpdated = true; + } // addEmailArrayToRole + + public void removeEmailToRole(String roleId) { + if (nvl(roleId).length() == 0) + return; + + for (int i = 0; i < emailToRoles.size(); i++) { + IdNameValue selRole = (IdNameValue) emailToRoles.get(i); + if (roleId.equals(selRole.getId())) { + infoUpdated = true; + emailToRoles.remove(i); + return; + } // if + } // for + } // addEmailToRole + + private void loadScheduleData(HttpServletRequest request) { + try { + StringBuffer query = new StringBuffer(""); + //query.append("SELECT rs.enabled_yn, TO_CHAR(rs.start_date, 'MM/DD/YYYY') start_date, TO_CHAR(rs.end_date, 'MM/DD/YYYY') end_date, TO_CHAR(rs.run_date, 'MM/DD/YYYY') run_date, NVL(TO_CHAR(rs.run_date, 'HH'), '12') run_hour, NVL(TO_CHAR(rs.run_date, 'MI'), '00') run_min, NVL(TO_CHAR(rs.run_date, 'AM'), 'AM') run_ampm, rs.recurrence, rs.conditional_yn, rs.notify_type, rs.max_row, rs.initial_formfields, rs.schedule_id, NVL(TO_CHAR(rs.end_date, 'HH'), '11') end_hour, NVL(TO_CHAR(rs.end_date, 'MI'), '45') end_min, NVL(TO_CHAR(rs.end_date, 'AM'), 'PM') end_ampm, encrypt_yn, attachment_yn FROM cr_report_schedule rs WHERE rs.rep_id = " + // + reportID); + String q_sql = Globals.getLoadScheduleData(); + q_sql = q_sql.replace("[reportID]", reportID); + query.append(q_sql); + + if(!AppUtils.isAdminUser(request)) + query.append(" and rs.sched_user_id = " + getScheduleUserID()); + if(nvl(getScheduleID()).length()>0) { + query.append(" and rs.schedule_id = " + getScheduleID()); + } + query.append(" order by rs.run_date desc "); + + DataSet ds = DbUtils + .executeQuery(query.toString()); + + if (ds.getRowCount() > 0) { + schedEnabled = nvl(ds.getString(0, 0), "N"); + startDate = nvl(ds.getString(0, 1)); + endDate = nvl(ds.getString(0, 2)); + runDate = nvl(ds.getString(0, 3)); + runHour = nvl(ds.getString(0, 4), "12"); + runMin = nvl(ds.getString(0, 5), "00"); + runAMPM = nvl(ds.getString(0, 6), "AM"); + recurrence = nvl(ds.getString(0, 7)); + conditional = nvl(ds.getString(0, 8), "N"); + //conditionSQL = nvl(ds.getString(0, 9)); + notify_type = nvl(ds.getString(0, 9), "1"); + downloadLimit = nvl(ds.getString(0, 10), "1000"); + //if(nvl(ds.getString(0, 13).) + formFields = nvl(ds.getString(0, 11)); + setScheduleID(ds.getString(0, 12)); + endHour = nvl(ds.getString(0, 13), "11"); + endMin = nvl(ds.getString(0, 14), "45"); + endAMPM = nvl(ds.getString(0, 15), "PM"); + encryptMode = nvl(ds.getString(0, "encrypt_yn"), "N"); + attachment = nvl(ds.getString(0, "attachment_yn"), "Y"); + conditionSQL = loadConditionalSQL(getScheduleID()); + } else { // if + //DataSet dsSeq = DbUtils.executeQuery("select SEQ_CR_REPORT_SCHEDULE.nextval from dual" ); + String n_sql = Globals.getNewScheduleData(); + DataSet dsSeq = DbUtils.executeQuery(n_sql); + String schedule_id = dsSeq.getString(0,0); + setScheduleID(schedule_id); + } + if(getScheduleID().length() > 0) { + //ds = DbUtils + // .executeQuery("SELECT rsu.user_id, fuser.last_name||', '||fuser.first_name, fuser.login_id FROM cr_report_schedule_users rsu, fn_user fuser WHERE rsu.rep_id = " + // + reportID + " AND rsu.schedule_id = " + getScheduleID() + " and rsu.user_id IS NOT NULL and rsu.user_id = fuser.user_id"); + + String t_sql = Globals.getLoadScheduleGetId(); + t_sql = t_sql.replace("[reportID]", reportID); + t_sql = t_sql.replace("[getScheduleID()]", getScheduleID()); + + ds = DbUtils.executeQuery(t_sql); + + for (int i = 0; i < ds.getRowCount(); i++){ + String nameToDisplay = ds.getString(i, 1); + if (Globals.getUseLoginIdInSchedYN()!= null && Globals.getUseLoginIdInSchedYN().equals("Y")) { + nameToDisplay = ds.getString(i, 2); + } + if(nameToDisplay!=null && nameToDisplay.length() > 0) + emailToUsers.add(new IdNameValue(ds.getString(i, 0), nameToDisplay)); + else + emailToUsers.add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1))); + } + Collections.sort(emailToUsers, new NameComparator()); + + //ds = DbUtils + // .executeQuery("SELECT rsu.role_id FROM cr_report_schedule_users rsu WHERE rsu.rep_id = " + // + reportID + " AND rsu.schedule_id = " + getScheduleID() + " AND rsu.role_id IS NOT NULL"); + + String r_sql = Globals.getLoadScheduleUsers(); + r_sql = r_sql.replace("[reportID]", reportID); + r_sql = r_sql.replace("[getScheduleID()]", getScheduleID()); + + ds = DbUtils.executeQuery(r_sql); + + for (int i = 0; i < ds.getRowCount(); i++) + emailToRoles.add(new IdNameValue(ds.getString(i, 0), AppUtils.getRoleName(ds + .getString(i, 0)))); + Collections.sort(emailToRoles, new NameComparator()); + + infoUpdated = false; + } + } catch (Exception e) { + throw new RuntimeException( + "[ReportSchedule.loadScheduleData] Unable to load Report " + reportID + + " schedule. Error: " + e.getMessage()); + } + } // loadScheduleData + + private void newScheduleData() { + try { + //DataSet dsSeq = DbUtils.executeQuery("select SEQ_CR_REPORT_SCHEDULE.nextval from dual" ); + String sql = Globals.getNewScheduleData(); + DataSet dsSeq = DbUtils.executeQuery(sql); + + String schedule_id = dsSeq.getString(0,0); + setScheduleID(schedule_id); + } catch (Exception e) { + throw new RuntimeException( + "[ReportSchedule.newScheduleData] Unable to load Report " + reportID + + " schedule. Error: " + e.getMessage()); + } + } // newScheduleData + + private String parseScheduleSQL(HttpServletRequest request, String sql) throws RaptorException { + DataSet ds = null; + + logger.debug(EELFLoggerDelegate.debugLogger, (sql)); + String[] reqParameters = Globals.getRequestParams().split(","); + String[] sessionParameters = Globals.getSessionParams().split(","); + String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(","); + javax.servlet.http.HttpSession session = request.getSession(); + ReportRuntime rr = (ReportRuntime) session.getAttribute(AppConstants.SI_REPORT_RUNTIME); + String userId = AppUtils.getUserID(request); + String dbType = ""; + String dbInfo = rr.getDBInfo(); + ReportParamValues paramValues = rr.getReportParamValues(); + int fieldCount = 0; + // For Daytona removing all formfields which has null param value + Pattern re1 = null; + Matcher matcher = null; + int index = 0; + int posFormField = 0; + int posAnd = 0; + if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { + try { + org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo(); + dbType = remDbInfo.getDBType(dbInfo); + } catch (Exception ex) { + throw new RaptorException(ex); + } + } + + sql = sql + " "; + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT "); + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE "); + sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND "); + + if (rr.getFormFieldList() != null) { + for (Iterator iter = rr.getFormFieldList().getFormField().iterator(); iter.hasNext();) { + + FormFieldType fft = (FormFieldType) iter.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = rr.getFormFieldDisplayName(fft); + if(!fft.getFieldType().equals(FormField.FFT_BLANK)) { + if (paramValues.isParameterMultiValue(fieldId)) { + String replaceValue = rr.formatListValue(fieldDisplay, nvl(paramValues.getParamValue(fieldId)), null, false, + true, null, paramValues.getParamBaseSQL(fieldId)); + if(replaceValue.length() > 0) { + sql = Utils.replaceInString(sql, fieldDisplay, replaceValue); + } else { + fieldCount++; + if(fieldCount == 1) { + //sql = sql + " "; + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT "); + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE "); + //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND "); + } + //sql = getReportSQL(); + while(sql.indexOf(fieldDisplay) > 0) { +/* sql = Utils.replaceInString(sql, "SELECT ", "select "); + sql = Utils.replaceInString(sql, "WHERE", "where"); + sql = Utils.replaceInString(sql, " AND ", " and "); +*/ + re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); + //re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\]", Pattern.DOTALL); +/* posFormField = sql.indexOf(fieldDisplay); + posAnd = sql.lastIndexOf("and", posFormField); + if(posAnd < 0) posAnd = 0; + else if (posAnd > 2) posAnd = posAnd - 2; + matcher = re1.matcher(sql); +*/ + posFormField = sql.indexOf(fieldDisplay); + int posSelectField = sql.lastIndexOf("SELECT ", posFormField); + int whereField = sql.indexOf(" WHERE" , posSelectField); + int andField = 0; + if(posFormField > whereField) + andField = sql.lastIndexOf(" AND ", posFormField); + if (posFormField > andField && andField > whereField) + posAnd = andField; + else + posAnd = 0; + matcher = re1.matcher(sql); + + + if (posAnd > 0 && matcher.find(posAnd-1)) { + //sql = Utils.replaceInString(sql, matcher.group(), " "); + matcher = re1.matcher(sql); + index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1; + + if(andField>0) + index = andField; + else + index = whereField; + if(index >= 0 && matcher.find(index-1)) { + sql = sql.replace(matcher.group(), " "); + } + } else { + + //sql = sql.replace + re1 = Pattern.compile("(^[\r\n]|[\\s])WHERE(.*?[^\r\n]*)\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); + matcher = re1.matcher(sql); + if(matcher.find(whereField-1)) { + matcher = re1.matcher(sql); + index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1; + if(index >= 0 && matcher.find(index-30)) { + sql = sql.replace(matcher.group(), " WHERE 1=1 "); + } + //sql = Utils.replaceInString(sql, matcher.group(), " where 1=1 "); + } /*else { + replaceValue = formatListValue("", Utils + .oracleSafe(nvl(paramValues.getParamValue(fieldId))), null, false, + true, null, paramValues.getParamBaseSQL(fieldId)); + sql = Utils.replaceInString(sql, fieldDisplay, replaceValue); + }*/ + + } + } + } + + //sql = Utils.replaceInString(sql, " select ", " SELECT "); + //sql = Utils.replaceInString(sql, " where ", " WHERE "); + //sql = Utils.replaceInString(sql, " and ", " AND "); + + } else { + String paramValue = ""; + if(paramValues.isParameterTextAreaValueAndModified(fieldId)) { + String value = ""; + value = nvl(paramValues + .getParamValue(fieldId)); +// value = Utils.oracleSafe(nvl(value)); +// if (!(dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT"))) { +// value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; +// value = Utils.replaceInString(value, "|", ","); +// paramValue = XSSFilter.filterRequestOnlyScript(value); +// } else if (nvl(value.trim()).length()>0) { +// value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; +// value = Utils.replaceInString(value, "|", ","); +// paramValue = XSSFilter.filterRequestOnlyScript(value); +// } + paramValue = value; + } else + paramValue = nvl(paramValues + .getParamValue(fieldId)); + + if (paramValue!=null && paramValue.length() > 0) { + if(paramValue.toLowerCase().trim().startsWith("select ")) { + paramValue = Utils.replaceInString(paramValue, "[LOGGED_USERID]", userId); + paramValue = Utils.replaceInString(paramValue, "[USERID]", userId); + paramValue = Utils.replaceInString(paramValue, "[USER_ID]", userId); + + paramValue = Utils.replaceInString(paramValue, "''", "'"); + ds = ConnectionUtils.getDataSet(paramValue, dbInfo); + if (ds.getRowCount() > 0) paramValue = ds.getString(0, 0); + } + logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED B4^^^^^^^^^ " + sql + " " + fft.getValidationType() + " " + fft.getFieldName() + " " + fft.getFieldId())); + if(fft!=null && (fft.getValidationType()!=null && (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) ||fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ||fft.getValidationType().equals(FormField.VT_DATE) ))) { + //System.out.println("paramValues.getParamValue(fieldId_Hr) Inside if " + fft.getValidationType() + " " + fieldDisplay); + if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue) +((nvl(paramValues + .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ):"")); + } + else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) { +/* System.out.println("paramValues.getParamValue(fieldId_Hr)" + paramValues + .getParamValue(fieldId+"_Hr") + " " + paramValues + .getParamValue(fieldId+"_Min")) ; +*/ sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue) + ((nvl(paramValues + .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ):"") + ((nvl(paramValues + .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(nvl(paramValues + .getParamValue(fieldId+"_Min") ) ) : "") ) ; + } + else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue) + ((nvl(paramValues + .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues + .getParamValue(fieldId+"_Hr") ) ):"") + ((nvl(paramValues + .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(nvl(paramValues + .getParamValue(fieldId+"_Min") ) ) : "") + ((nvl(paramValues + .getParamValue(fieldId+"_Sec") ).length()>0)?":"+addZero(nvl(paramValues + .getParamValue(fieldId+"_Sec") ) ) : "" ) ) ; + } else { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } + + + } else { + if(paramValue!=null && paramValue.length() > 0) { + if(sql.indexOf("'"+fieldDisplay+"'")!=-1 || sql.indexOf("'"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"'")!=-1 + || sql.indexOf("'%"+fieldDisplay+"%'")!=-1 || sql.indexOf("'%"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"%'")!=-1 + || sql.indexOf("'_"+fieldDisplay+"_'")!=-1 || sql.indexOf("'_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_'")!=-1 + || sql.indexOf("'%_"+fieldDisplay+"_%'")!=-1 || sql.indexOf("^"+fieldDisplay+"^")!=-1 || sql.indexOf("'%_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_%'")!=-1) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } else { + if(sql.indexOf(fieldDisplay)!=-1) { + if(nvl(paramValue).length()>0) { + try { + double vD = Double.parseDouble(paramValue); + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + + } catch (NumberFormatException ex) { + if (/*dbType.equals("DAYTONA") &&*/ sql.trim().toUpperCase().startsWith("SELECT")) { + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } else + throw new UserDefinedException("Expected number, Given String for the form field \"" + fieldDisplay+"\""); + } + /*sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL"));*/ + } else + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + + } + } + } + else { + if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) { + sql = sql + " "; + re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); + posFormField = sql.indexOf(fieldDisplay); + posAnd = sql.lastIndexOf(" AND ", posFormField); + if(posAnd < 0) posAnd = 0; + else if (posAnd > 2) posAnd = posAnd - 2; + matcher = re1.matcher(sql); + if (matcher.find(posAnd)) { + sql = sql.replace(matcher.group(), ""); + } + } else { + sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + sql = Utils.replaceInString(sql, fieldDisplay, nvl( + paramValue, "NULL")); + } + } + } + + } + + if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) { + sql = sql + " "; + re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); //+[\'\\)|\'|\\s] + posFormField = sql.indexOf(fieldDisplay); + posAnd = sql.lastIndexOf(" AND ", posFormField); + if(posAnd < 0) posAnd = 0; + else if (posAnd > 2) posAnd = posAnd - 2; + matcher = re1.matcher(sql); + if (matcher.find(posAnd)) { + sql = sql.replace(matcher.group(), " "); + } + } else { + + logger.debug(EELFLoggerDelegate.debugLogger, ("ParamValue |" + paramValue + "| Sql |" + sql + "| Multi Value |" + paramValues.isParameterMultiValue(fieldId))); + sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + sql = Utils.replaceInString(sql, fieldDisplay , nvl( + paramValue, "NULL")); + logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED AFTER^^^^^^^^^ " + sql)); + } + + } // else + } // if BLANK + } // for + if(request != null ) { + for (int i = 0; i < reqParameters.length; i++) { + if(!reqParameters[i].startsWith("ff")) { + if (nvl(request.getParameter(reqParameters[i].toUpperCase())).length() > 0) + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) ); + } + else + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) ); + } + + for (int i = 0; i < scheduleSessionParameters.length; i++) { + if(nvl(request.getParameter(scheduleSessionParameters[i])).trim().length()>0 ) + sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) ); + } + } + if(session != null ) { + for (int i = 0; i < sessionParameters.length; i++) { + //if(!sessionParameters[i].startsWith("ff")) + // paramValue = Utils.replaceInString(paramValue, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); + // else { + logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]))); + sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + //} + } + } + } else { + logger.debug(EELFLoggerDelegate.debugLogger, ("BEFORE LOGGED USERID REPLACE " + sql)); + //sql = Utils.replaceInString(sql, "'[logged_userId]'", "'"+userId+"'"); + //debugLogger.debug("Replacing string 2 " + sql); + sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId); + sql = Utils.replaceInString(sql, "[USERID]", userId); + sql = Utils.replaceInString(sql, "[USER_ID]", userId); + logger.debug(EELFLoggerDelegate.debugLogger, ("AFTER LOGGED USERID REPLACE " + sql)); + // Added for Simon's GM Project where they need to get page_id in their query + logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED no formfields " + sql)); + if(request != null ) { + for (int i = 0; i < reqParameters.length; i++) { + sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) ); + } + } + if(session != null ) { + for (int i = 0; i < sessionParameters.length; i++) { + logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]))); + sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); + } + } + } + // if it is not multiple select and ParamValue is empty this is the place it can be replaced. + sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId); + sql = Utils.replaceInString(sql, "[USERID]", userId); + sql = Utils.replaceInString(sql, "[USER_ID]", userId); + logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED no formfields after" + sql)); + //debugLogger.debug("Replacing String 2 "+ sql); + //debugLogger.debug("Replaced String " + sql); + + sql = Pattern.compile("([\n][\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" "); + return sql; + + } + public void persistScheduleData(Connection conn, HttpServletRequest request) throws RaptorException { + if (!infoUpdated) + return; + if (reportID.equals("-1")) + return; + + + try { + String sched_id = ""; + StringBuffer query = new StringBuffer(""); + query.append(" SELECT 1 FROM cr_report_schedule WHERE rep_id = " + reportID + " and schedule_id = " + getScheduleID()); + if(!AppUtils.isAdminUser(request)) + query.append(" and sched_user_id = " + getScheduleUserID()); + DataSet ds = DbUtils.executeQuery(conn, query.toString()); + if (ds.getRowCount() > 0) { + StringBuffer sb = new StringBuffer(); + sb.append("UPDATE cr_report_schedule SET enabled_yn = '"); + sb.append(getSchedEnabled()); + sb.append("', start_date = "); + if (getStartDate().length() > 0) { + sb.append("TO_DATE('"); + sb.append(getStartDate()); + sb.append("', 'MM/DD/YYYY')"); + } else + sb.append("NULL"); + sb.append(", end_date = "); + if (getEndDate().length() > 0) { + sb.append("TO_DATE('"); + sb.append(getEndDate()); + sb.append(" "); + sb.append(getEndHour()); + sb.append(":"); + sb.append(getEndMin()); + sb.append(" "); + sb.append(getEndAMPM()); + sb.append("', 'MM/DD/YYYY HH:MI AM')"); + } else + sb.append("NULL"); + sb.append(", run_date = "); + if (getRunDate().length() > 0) { + sb.append("TO_DATE('"); + sb.append(getRunDate()); + sb.append(" "); + sb.append(getRunHour()); + sb.append(":"); + sb.append(getRunMin()); + sb.append(" "); + sb.append(getRunAMPM()); + sb.append("', 'MM/DD/YYYY HH:MI AM')"); + } else + sb.append("NULL"); + sb.append(", recurrence = "); + if (getRecurrence().length() > 0) { + sb.append("'"); + sb.append(getRecurrence()); + sb.append("'"); + } else + sb.append("NULL"); + sb.append(", conditional_yn = '"); + sb.append(getConditional()); + //sb.append("', condition_sql = "); + sb.append("'"); +/* if (getConditionSQL().length() > 0) { + sb.append("'"); + sb.append(parseScheduleSQL(request, Utils.oracleSafe(getConditionSQL()))); + sb.append("'"); + } else + sb.append("NULL"); +*/ + sb.append(", notify_type = "); + sb.append(getNotify_type()); + sb.append(", encrypt_yn = '"); + sb.append(getEncryptMode()+"'"); + sb.append(", attachment_yn = '"); + sb.append(getAttachmentMode()+"'"); + sb.append(", max_row = "); + sb.append(getDownloadLimit()); + sb.append(", initial_formFields = '"); + sb.append(getFormFields()+"'"); + sb.append(", processed_formfields = ''"); + sb.append(" WHERE rep_id = "); + sb.append(reportID + " and sched_user_id = "); + sb.append(getScheduleUserID()); + sb.append(" and schedule_id = "); + sb.append(getScheduleID()); + + DbUtils.executeUpdate(conn, sb.toString()); + } else { + //DataSet dsSeq = DbUtils.executeQuery("select seq_cr_report_schedule.nextval from dual " ); + String w_sql = Globals.getNewScheduleData(); + DataSet dsSeq = DbUtils.executeQuery(w_sql); + String schedule_id = dsSeq.getString(0,0); + setScheduleID(schedule_id); + StringBuffer sb = new StringBuffer(); + sb.append("INSERT INTO cr_report_schedule (schedule_id, sched_user_id, rep_id, enabled_yn, start_date, end_date, run_date, recurrence, conditional_yn, notify_type, max_row, initial_formfields, encrypt_yn, attachment_yn) VALUES("); + sb.append(getScheduleID() + ", "); + sb.append(getScheduleUserID() + ", "); + sb.append(reportID); + sb.append(", '"); + sb.append(getSchedEnabled()); + sb.append("', "); + if (getStartDate().length() > 0) { + sb.append("TO_DATE('"); + sb.append(getStartDate()); + sb.append("', 'MM/DD/YYYY')"); + } else + sb.append("NULL"); + sb.append(", "); + if (getEndDate().length() > 0) { + sb.append("TO_DATE('"); + sb.append(getEndDate()); + sb.append(" "); + sb.append(getEndHour()); + sb.append(":"); + sb.append(getEndMin()); + sb.append(" "); + sb.append(getEndAMPM()); + sb.append("', 'MM/DD/YYYY HH:MI AM')"); + } else + sb.append("NULL"); + sb.append(", "); + if (getRunDate().length() > 0) { + sb.append("TO_DATE('"); + sb.append(getRunDate()); + sb.append(" "); + sb.append(getRunHour()); + sb.append(":"); + sb.append(getRunMin()); + sb.append(" "); + sb.append(getRunAMPM()); + sb.append("', 'MM/DD/YYYY HH:MI AM')"); + } else + sb.append("NULL"); + sb.append(", "); + if (getRecurrence().length() > 0) { + sb.append("'"); + sb.append(getRecurrence()); + sb.append("'"); + } else + sb.append("NULL"); + sb.append(", '"); + sb.append(getConditional()); + sb.append("', "); +/* if (getConditionSQL().length() > 0) { + sb.append("'"); + sb.append(parseScheduleSQL(request, Utils.oracleSafe(getConditionSQL()))); + sb.append("'"); + } else + sb.append("NULL"); + sb.append(", "); +*/ + sb.append(getNotify_type()); + sb.append(", "); + sb.append(getDownloadLimit()); + sb.append(", '"); + sb.append(getFormFields()+"'"); + sb.append(",'"); + sb.append(getEncryptMode()+"'"); + sb.append(",'"); + sb.append(getAttachmentMode()+"'"); + sb.append(")"); + DbUtils.executeUpdate(conn, sb.toString()); + + } // else + + + //DbUtils.executeUpdate(conn, + // "DELETE cr_report_schedule_users WHERE rep_id = " + reportID+ " and schedule_id = " + getScheduleID()); + + String d_sql = Globals.getExecuteUpdate(); + d_sql = d_sql.replace("[reportID]", reportID); + d_sql = d_sql.replace("[getScheduleID()]", getScheduleID()); + + DbUtils.executeUpdate(conn, d_sql); + + for (int i = 0; i < emailToUsers.size(); i++){ + //DbUtils.executeUpdate(conn, + // "INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES(" + // + getScheduleID() + ", " + // + reportID + ", " + // + ((IdNameValue) emailToUsers.get(i)).getId() + ", NULL, " + // + (i + 1) + ")"); + + String sql = Globals.getExecuteUpdateUsers(); + sql = sql.replace("[getScheduleID()]", getScheduleID()); + sql = sql.replace("[reportID]", reportID); + sql = sql.replace("[emailToUsers.get(i)).getId()]", ((IdNameValue) emailToUsers.get(i)).getId()); + sql = sql.replace("[(i + 1)]", String.valueOf(i + 1)); + DbUtils.executeUpdate(conn, sql); + + } + for (int i = 0; i < emailToRoles.size(); i++){ + //DbUtils.executeUpdate(conn, + // "INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES(" + // + getScheduleID() +", " + // + reportID + ", NULL, " + // + ((IdNameValue) emailToRoles.get(i)).getId() + ", " + // + (emailToUsers.size() + i + 1) + ")"); + + String sql = Globals.getExecuteUpdateRoles(); + sql = sql.replace("[getScheduleID()]", getScheduleID()); + sql = sql.replace("[reportID]", reportID); + sql = sql.replace("[emailToRoles.get(i)).getId()]", ((IdNameValue) emailToRoles.get(i)).getId()); + sql = sql.replace("[((emailToUsers.size() + i + 1)]", String.valueOf(emailToUsers.size() + i + 1)); + + DbUtils.executeUpdate(conn, sql); + } + //if (conn == null) + DbUtils.commitTransaction(conn); + + persistConditionSql(conn, getScheduleID(), parseScheduleSQL(request, getConditionSQL())); + + + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " - schedule data updated")); + //DbUtils.executeUpdate(conn, + // "INSERT into cr_schedule_activity_log (schedule_id, notes, run_time) values ("+getScheduleID()+",'Submitted:Schedule',TO_DATE('"+ getRunDate()+" "+ getRunHour()+":"+getRunMin()+" "+getRunAMPM()+"', 'MM/DD/YYYY HH:MI AM'))"); + String e_sql = Globals.getExecuteUpdateActivity(); + e_sql = e_sql.replace("[getScheduleID()]", getScheduleID()); + e_sql = e_sql.replace("[getRunDate()]", getRunDate()); + e_sql = e_sql.replace("[getRunHour()]", getRunHour()); + e_sql = e_sql.replace("[getRunMin()]", getRunMin()); + e_sql = e_sql.replace("[getRunAMPM()]", getRunAMPM()); + + DbUtils.executeUpdate(conn, e_sql); + + infoUpdated = false; + + } catch (RaptorException e) { + if (conn != null) + DbUtils.rollbackTransaction(conn); + throw e; + } // catch + + } // persistScheduleData + + //deleting the schedule - Start + public void deleteScheduleData(Connection conn) throws RaptorException { + if (reportID.equals("-1")) + return; + + Connection connection = (conn != null) ? conn : DbUtils.startTransaction(); + String sched_id = ""; + try { + //DataSet ds = DbUtils.executeQuery(connection, + // "SELECT 1 FROM cr_report_schedule WHERE rep_id = " + reportID +" and sched_user_id = " + getScheduleUserID() + " and schedule_id = " + getScheduleID()); + String a_sql = Globals.getDeleteScheduleData(); + a_sql = a_sql.replace("[reportID]", reportID); + a_sql = a_sql.replace("[getScheduleUserID()]", getScheduleUserID()); + a_sql = a_sql.replace("[getScheduleID()]", getScheduleID()); + DataSet ds = DbUtils.executeQuery(connection, a_sql); + + if (ds.getRowCount() > 0) { + //DbUtils.executeUpdate(connection, + // "DELETE cr_report_schedule_users WHERE rep_id = " + reportID+ " and schedule_id = " + getScheduleID()); + String b_sql = Globals.getDeleteScheduleDataUsers(); + b_sql = b_sql.replace("[reportID]", reportID); + b_sql = b_sql.replace("[getScheduleID()]", getScheduleID()); + + DbUtils.executeUpdate(connection, b_sql); + + StringBuffer sb = new StringBuffer(); + String c_sql = Globals.getDeleteScheduleDataId(); + c_sql = c_sql.replace("[reportID]", reportID); + c_sql = c_sql.replace("[getScheduleUserID()]", getScheduleUserID()); + c_sql = c_sql.replace("[getScheduleID()]", getScheduleID()); + + sb.append(c_sql); + //sb.append("DELETE FROM cr_report_schedule where rep_id = " + reportID +" and sched_user_id = " + getScheduleUserID() + " and schedule_id = " + getScheduleID()); + + DbUtils.executeUpdate(connection, sb.toString()); + } + if (conn == null) + DbUtils.commitTransaction(connection); + + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " - schedule data deleted")); + } catch (RaptorException e) { + if (conn == null) + DbUtils.rollbackTransaction(connection); + throw e; + } // catch + finally { + if (conn == null) + DbUtils.clearConnection(connection); + } + } //deleteScheduleData + + public String getScheduleUserID() { + return scheduleUserID; + } + + public void setScheduleUserID(String scheduleUserID) { + this.scheduleUserID = scheduleUserID; + } + + public String getScheduleID() { + return nvl(scheduleID); + } + + public void setScheduleID(String scheduleID) { + this.scheduleID = scheduleID; + } + + public String getEndAMPM() { + return endAMPM; + } + + public void setEndAMPM(String endAMPM) { + if (nvl(endAMPM).equals(this.endAMPM)) + return; + infoUpdated = true; + this.endAMPM = nvl(endAMPM, "PM"); + } + + public String getEndHour() { + return endHour; + } + + public void setEndHour(String endHour) { + if (nvl(endHour).equals(this.endHour)) + return; + infoUpdated = true; + this.endHour = nvl(endHour, "11"); + } + + public String getEndMin() { + return endMin; + } + + public void setEndMin(String endMin) { + if (nvl(endMin).equals(this.endMin)) + return; + infoUpdated = true; + this.endMin = nvl(endMin, "45"); + } + + public static boolean isNull(String a) { + if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null")) + return true; + else + return false; + } + + public String addZero(String num) { + int numInt = 0; + try { + numInt = Integer.parseInt(num); + }catch(NumberFormatException ex){ + numInt = 0; + } + if(numInt < 10) return "0"+numInt; + else return ""+numInt; + } + + public static String loadConditionalSQL(String scheduleId) + throws RaptorException { + StringBuffer sb = new StringBuffer(); + + PreparedStatement stmt = null; + + ResultSet rs = null; + String condition_sql = ""; + Connection connection = null; + + try { + connection = DbUtils.getConnection(); + + //String sql = "SELECT condition_large_sql FROM cr_report_schedule WHERE schedule_id=?"; + String sql = Globals.getLoadCondSql(); + stmt = connection.prepareStatement(sql); + stmt.setString(1,scheduleId); + rs = stmt.executeQuery(); + if(Globals.isWeblogicServer()) { + java.sql.Clob clob= null; + Object obj = null; + if (rs.next()) { + clob = rs.getClob(1); + } + else + throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database"); + + int len = 0; + char[] buffer = new char[512]; + Reader in = null; + in = new InputStreamReader(clob.getAsciiStream()); + // if(obj instanceof oracle.sql.CLOB) { + // in = ((oracle.sql.CLOB) obj).getCharacterStream(); + // } else if (obj instanceof weblogic.jdbc.wrapper.Clob) { + // in = ((weblogic.jdbc.base.BaseClob) obj).getCharacterStream(); + // } + while ((len = in.read(buffer)) != -1) + sb.append(buffer, 0, len); + in.close(); + } else if (Globals.isPostgreSQL() || Globals.isMySQL()) { + String clob= null; + Object obj = null; + if (rs.next()) { + sb.append(rs.getString(1)); + } + else + throw new RaptorException("Schedule ID " + scheduleId + " not found in the database"); + } else { + /*oracle.sql.CLOB clob = null; + if (rs.next()) + clob = (oracle.sql.CLOB) rs.getObject(1); + else + throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database"); + int len = 0; + char[] buffer = new char[512]; + Reader in = null; + if(clob!=null) { + in = clob.getCharacterStream(); + while ((len = in.read(buffer)) != -1) + sb.append(buffer, 0, len); + in.close(); + }*/ + throw new RaptorException("only maria db support for this "); + + } + } catch (SQLException ex) { + try { + StringBuffer query = new StringBuffer(""); + + query.append(" SELECT condition_sql FROM cr_report_schedule WHERE schedule_id = " + scheduleId); + DataSet ds = DbUtils.executeQuery(query.toString()); + if(ds.getRowCount()>0) { + condition_sql = ds.getString(0,0); + } + return condition_sql; + //throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } catch (RaptorException e) { + DbUtils.rollbackTransaction(connection); + throw e; + } // catch + + finally { + DbUtils.clearConnection(connection); + } + + } catch (IOException ex) { + throw new RaptorRuntimeException (ex.getMessage(), ex.getCause()); + } finally { + try { + if (connection != null) + DbUtils.clearConnection(connection); + if(rs!=null) + rs.close(); + if(stmt!=null) + stmt.close(); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + return sb.toString(); + } // loadConditionalSQL + + private static void persistConditionSql(Connection connection, String scheduleId, String conditional_sql) throws RaptorException { + PreparedStatement stmt = null; + ResultSet rs = null; + + try { + //String sql = "update cr_report_schedule set condition_large_sql = EMPTY_CLOB() where schedule_id = " + scheduleId; + String sql = Globals.getPersistCondSqlUpdate(); + sql = sql.replace("[scheduleId]", scheduleId); + + DbUtils.executeUpdate(sql); + //sql = "SELECT condition_large_sql FROM cr_report_schedule cr WHERE schedule_id=? FOR UPDATE"; + sql = Globals.getPersistCondSqlLarge(); + stmt = connection.prepareStatement(sql); + stmt.setString(1,scheduleId); + rs = stmt.executeQuery(); + Writer out = null; + /*if(Globals.isWeblogicServer()) { + java.sql.Clob clob = null; + if (rs.next()) + clob = rs.getClob(1); + else + throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database"); + + if (clob.length() > conditional_sql.length()) + clob.truncate(0); + //clob.trim(reportXML.length()); + out = ((weblogic.jdbc.vendor.oracle.OracleThinClob)clob).getCharacterOutputStream(); + } else*/ + if (Globals.isPostgreSQL() || Globals.isMySQL()) { + if (rs.next()) { + rs.updateString(1,conditional_sql); + rs.updateRow(); + //sb.append(rs.getString(1)); + } + else + throw new RaptorException("Schedule ID " + scheduleId + " not found in the database"); + } else {/* + oracle.sql.CLOB clob = null; + if (rs.next()) + clob = (oracle.sql.CLOB) rs.getObject(1); + else + throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database"); + + if (clob.length() > conditional_sql.length()) + clob.trim(conditional_sql.length()); + out = clob.getCharacterOutputStream();*/ + throw new RaptorException("only maria db support for this "); + + } + out.write(conditional_sql); + out.flush(); + out.close(); + } catch (RaptorException ex) { + if(ex.getMessage().indexOf("invalid identifier")!= -1) { + try { + //String sql = "update cr_report_schedule set condition_sql = ? where schedule_id = " + scheduleId; + String sql = Globals.getPersistCondSqlSet(); + sql = sql.replace("[scheduleId]", scheduleId); + stmt = connection.prepareStatement(sql); + stmt.setString(1,conditional_sql); + stmt.executeUpdate(); + connection.commit(); + } catch (SQLException ex1) { + try { + connection.rollback(); + } catch (SQLException ex2) {} + + } + } else { + try { + connection.rollback(); + } catch (SQLException ex2) { + throw new ReportSQLException (ex2.getMessage(), ex2.getCause()); + } + } + } catch (SQLException ex) { + try { + connection.rollback(); + } catch (SQLException ex2) { + throw new ReportSQLException (ex2.getMessage(), ex2.getCause()); + } + } catch (IOException ex) { + throw new RaptorRuntimeException (ex.getMessage(), ex.getCause()); + } finally { + try { + if(rs!=null) + rs.close(); + if(stmt!=null) + stmt.close(); + } catch (SQLException ex) { + throw new ReportSQLException (ex.getMessage(), ex.getCause()); + } + } + } // persistConditionSql + + /** + * Used to get encryption mode + * @return the encryptMode + */ + public String getEncryptMode() { + return encryptMode; + } + + /** + * Used to set encryption mode + * @param encryptMode the encryptMode to set + */ + public void setEncryptMode(String encryptMode) { + this.encryptMode = encryptMode; + infoUpdated = true; + } + + + /** + * Used to get Attachment mode + * @return the attachment + */ + public String getAttachmentMode() { + return attachment; + } + + public boolean isAttachmentMode() { + return nvl(attachment).toUpperCase().startsWith("Y"); + } + + /** + * Used to set Attachment mode + * @param attachment to set + */ + public void setAttachmentMode(String attachment) { + this.attachment = attachment; + infoUpdated = true; + } +} // ReportSchedule diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/SecurityEntry.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/SecurityEntry.java new file mode 100644 index 00000000..c5edb12a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/SecurityEntry.java @@ -0,0 +1,44 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.model.base.*; + +public class SecurityEntry extends IdNameValue { + private boolean readOnly = true; + + public SecurityEntry() { + super(); + } + + public SecurityEntry(String id, String name, boolean readOnly) { + super(id, name); + setReadOnly(readOnly); + } // SecurityEntry + + public boolean isReadOnly() { + return readOnly; + } + + public void setReadOnly(boolean readOnly) { + this.readOnly = readOnly; + } + +} // SecurityEntry diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableJoin.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableJoin.java new file mode 100644 index 00000000..6022d5a1 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableJoin.java @@ -0,0 +1,67 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.RaptorObject; + +public class TableJoin extends RaptorObject { + private String srcTableName = null; + + private String destTableName = null; + + private String joinExpr = null; + + public TableJoin() { + super(); + } + + public TableJoin(String srcTableName, String destTableName, String joinExpr) { + this(); + + setSrcTableName(srcTableName); + setDestTableName(destTableName); + setJoinExpr(joinExpr); + } // TableJoin + + public String getSrcTableName() { + return srcTableName; + } + + public String getDestTableName() { + return destTableName; + } + + public String getJoinExpr() { + return joinExpr; + } + + public void setSrcTableName(String srcTableName) { + this.srcTableName = srcTableName; + } + + public void setDestTableName(String destTableName) { + this.destTableName = destTableName; + } + + public void setJoinExpr(String joinExpr) { + this.joinExpr = joinExpr; + } + +} // TableJoin diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableSource.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableSource.java new file mode 100644 index 00000000..dc5b385a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/TableSource.java @@ -0,0 +1,101 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition; + +import org.openecomp.portalsdk.analytics.RaptorObject; + +public class TableSource extends RaptorObject { + private String tableName = null; + + private String displayName = null; + + private String pkFields = null; + + private String viewAction = null; + + private String isLargeData = null; + + private String filterSql = null; + + public TableSource() { + super(); + } + + public TableSource(String tableName, String displayName, String pkFields, + String viewAction, String isLargeData, String filterSql) { + this(); + + setTableName(tableName); + setDisplayName(displayName); + setPkFields(pkFields); + setViewAction(viewAction); + setIsLargeData(isLargeData); + setFilterSql(filterSql); + } // TableSource + + public String getTableName() { + return tableName; + } + + public String getDisplayName() { + return displayName; + } + + public String getPkFields() { + return pkFields; + } + + public String getViewAction() { + return viewAction; + } + + public String getIsLargeData() { + return isLargeData; + } + + public String getFilterSql() { + return filterSql; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public void setPkFields(String pkFields) { + this.pkFields = pkFields; + } + + public void setViewAction(String viewAction) { + this.viewAction = viewAction; + } + + public void setIsLargeData(String isLargeData) { + this.isLargeData = isLargeData; + } + + public void setFilterSql(String filterSql) { + this.filterSql = filterSql; + } + +} // TableSource diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnEditJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnEditJSON.java new file mode 100644 index 00000000..4e08a697 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnEditJSON.java @@ -0,0 +1,110 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +public class ColumnEditJSON implements WizardJSON { + + private String tabId; + private String tabName; + + private String colId; + private String colName; + private String displayAlignment; + private String displayHeaderAlignment; + private boolean sortable; + private boolean visible; + + private String drilldownURL; + private String drilldownParams; + private String drilldownType; + + public String getTabId() { + return tabId; + } + public void setTabId(String tabId) { + this.tabId = tabId; + } + public String getTabName() { + return tabName; + } + public void setTabName(String tabName) { + this.tabName = tabName; + } + public String getColId() { + return colId; + } + public void setColId(String colId) { + this.colId = colId; + } + public String getColName() { + return colName; + } + public void setColName(String colName) { + this.colName = colName; + } + public String getDisplayAlignment() { + return displayAlignment; + } + public void setDisplayAlignment(String displayAlignment) { + this.displayAlignment = displayAlignment; + } + public String getDisplayHeaderAlignment() { + return displayHeaderAlignment; + } + public void setDisplayHeaderAlignment(String displayHeaderAlignment) { + this.displayHeaderAlignment = displayHeaderAlignment; + } + public boolean isSortable() { + return sortable; + } + public void setSortable(boolean sortable) { + this.sortable = sortable; + } + public boolean isVisible() { + return visible; + } + public void setVisible(boolean visible) { + this.visible = visible; + } + public String getDrilldownURL() { + return drilldownURL; + } + public void setDrilldownURL(String drilldownURL) { + this.drilldownURL = drilldownURL; + } + public String getDrilldownParams() { + return drilldownParams; + } + public void setDrilldownParams(String drilldownParams) { + this.drilldownParams = drilldownParams; + } + public String getDrilldownType() { + return drilldownType; + } + public void setDrilldownType(String drilldownType) { + this.drilldownType = drilldownType; + } + + + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnJSON.java new file mode 100644 index 00000000..8f83c3ea --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ColumnJSON.java @@ -0,0 +1,41 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +public class ColumnJSON implements ElementJSON { + + private String id; + private String name; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/DefinitionJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/DefinitionJSON.java new file mode 100644 index 00000000..68211005 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/DefinitionJSON.java @@ -0,0 +1,215 @@ +package org.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.List; + +public class DefinitionJSON implements WizardJSON { + + private String tabName; + private String tabId; + + private String reportId; + private String reportName; + private String reportDescr; + private String reportType; + private String dbInfo; + private String formHelpText; + private Integer pageSize; + private List displayArea = null; + private Boolean hideFormFieldsAfterRun; + private Integer maxRowsInExcelCSVDownload; + private Integer frozenColumns; + private String dataGridAlign; + private String emptyMessage; + private String dataContainerHeight; + private String dataContainerWidth; + private List displayOptions = null; + private Boolean runtimeColSortDisabled; + private Integer numFormCols; + private String reportTitle; + private String reportSubTitle; + + @Override + public String getTabName() { + return tabName; + } + + @Override + public void setTabName(String tabName) { + this.tabName = tabName; + } + + @Override + public String getTabId() { + return tabId; + } + + @Override + public void setTabId(String tabId) { + this.tabId = tabId; + } + + + + public String getReportId() { + return reportId; + } + + public void setReportId(String reportId) { + this.reportId = reportId; + } + + public String getReportName() { + return reportName; + } + + public void setReportName(String reportName) { + this.reportName = reportName; + } + + public String getReportDescr() { + return reportDescr; + } + + public void setReportDescr(String reportDescr) { + this.reportDescr = reportDescr; + } + + public String getReportType() { + return reportType; + } + + public void setReportType(String reportType) { + this.reportType = reportType; + } + + public String getDbInfo() { + return dbInfo; + } + + public void setDbInfo(String dbInfo) { + this.dbInfo = dbInfo; + } + + public String getFormHelpText() { + return formHelpText; + } + + public void setFormHelpText(String formHelpText) { + this.formHelpText = formHelpText; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public List getDisplayArea() { + return displayArea; + } + + public void setDisplayArea(List displayArea) { + this.displayArea = displayArea; + } + + public Boolean getHideFormFieldsAfterRun() { + return hideFormFieldsAfterRun; + } + + public void setHideFormFieldsAfterRun(Boolean hideFormFieldsAfterRun) { + this.hideFormFieldsAfterRun = hideFormFieldsAfterRun; + } + + public Integer getMaxRowsInExcelCSVDownload() { + return maxRowsInExcelCSVDownload; + } + + public void setMaxRowsInExcelCSVDownload(Integer maxRowsInExcelCSVDownload) { + this.maxRowsInExcelCSVDownload = maxRowsInExcelCSVDownload; + } + + public Integer getFrozenColumns() { + return frozenColumns; + } + + public void setFrozenColumns(Integer frozenColumns) { + this.frozenColumns = frozenColumns; + } + + public String getDataGridAlign() { + return dataGridAlign; + } + + public void setDataGridAlign(String dataGridAlign) { + this.dataGridAlign = dataGridAlign; + } + + public String getEmptyMessage() { + return emptyMessage; + } + + public void setEmptyMessage(String emptyMessage) { + this.emptyMessage = emptyMessage; + } + + public String getDataContainerHeight() { + return dataContainerHeight; + } + + public void setDataContainerHeight(String dataContainerHeight) { + this.dataContainerHeight = dataContainerHeight; + } + + public String getDataContainerWidth() { + return dataContainerWidth; + } + + public void setDataContainerWidth(String dataContainerWidth) { + this.dataContainerWidth = dataContainerWidth; + } + + public List getDisplayOptions() { + return displayOptions; + } + + public void setDisplayOptions(List displayOptions) { + this.displayOptions = displayOptions; + } + + public Boolean getRuntimeColSortDisabled() { + return runtimeColSortDisabled; + } + + public void setRuntimeColSortDisabled(Boolean runtimeColSortDisabled) { + this.runtimeColSortDisabled = runtimeColSortDisabled; + } + + public Integer getNumFormCols() { + return numFormCols; + } + + public void setNumFormCols(Integer numFormCols) { + this.numFormCols = numFormCols; + } + + public String getReportTitle() { + return reportTitle; + } + + public void setReportTitle(String reportTitle) { + this.reportTitle = reportTitle; + } + + public String getReportSubTitle() { + return reportSubTitle; + } + + public void setReportSubTitle(String reportSubTitle) { + this.reportSubTitle = reportSubTitle; + } + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ElementJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ElementJSON.java new file mode 100644 index 00000000..aba1e8b4 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ElementJSON.java @@ -0,0 +1,33 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.ArrayList; +import java.util.Map; + +import org.openecomp.portalsdk.analytics.view.ColumnHeader; + +public interface ElementJSON { + + // To be defined by child class + public String getId(); + public String getName(); + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/FormEditJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/FormEditJSON.java new file mode 100644 index 00000000..47b6d1b0 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/FormEditJSON.java @@ -0,0 +1,113 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.List; + +public class FormEditJSON implements WizardJSON { + + private String tabId; + private String tabName; + + private String fieldId; + private String fieldName; + private String fieldType; + private boolean visible; + private String defaultValue; + private String fieldDefaultSQL; + private String fieldSQL; + private String validationType; + private List predefinedValueList; + + + public String getTabId() { + return tabId; + } + public void setTabId(String tabId) { + this.tabId = tabId; + } + public String getTabName() { + return tabName; + } + public void setTabName(String tabName) { + this.tabName = tabName; + } + + + public String getFieldId() { + return fieldId; + } + public void setFieldId(String fieldId) { + this.fieldId = fieldId; + } + public String getFieldName() { + return fieldName; + } + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public String getFieldType() { + return fieldType; + } + public void setFieldType(String fieldType) { + this.fieldType = fieldType; + } + public boolean isVisible() { + return visible; + } + public void setVisible(boolean visible) { + this.visible = visible; + } + public String getDefaultValue() { + return defaultValue; + } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + public String getFieldDefaultSQL() { + return fieldDefaultSQL; + } + public void setFieldDefaultSQL(String fieldDefaultSQL) { + this.fieldDefaultSQL = fieldDefaultSQL; + } + public String getValidationType() { + return validationType; + } + public void setValidationType(String validationType) { + this.validationType = validationType; + } + public List getPredefinedValueList() { + return predefinedValueList; + } + public void setPredefinedValueList(List predefinedValueList) { + this.predefinedValueList = predefinedValueList; + } + public String getFieldSQL() { + return fieldSQL; + } + public void setFieldSQL(String fieldSQL) { + this.fieldSQL = fieldSQL; + } + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/IdNameBooleanJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/IdNameBooleanJSON.java new file mode 100644 index 00000000..50add1f4 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/IdNameBooleanJSON.java @@ -0,0 +1,32 @@ +package org.openecomp.portalsdk.analytics.model.definition.wizard; + +public class IdNameBooleanJSON { + + private String id; + private String name; + private boolean selected; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public boolean isSelected() { + return selected; + } + public void setSelected(boolean selected) { + this.selected = selected; + } + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ImportJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ImportJSON.java new file mode 100644 index 00000000..282b7c41 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ImportJSON.java @@ -0,0 +1,54 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.List; + +public class ImportJSON implements WizardJSON { + + private String tabId; + private String tabName; + + private String reportXML; + + + public String getTabId() { + return tabId; + } + public void setTabId(String tabId) { + this.tabId = tabId; + } + public String getTabName() { + return tabName; + } + public void setTabName(String tabName) { + this.tabName = tabName; + } + public String getReportXML() { + return reportXML; + } + public void setReportXML(String reportXML) { + this.reportXML = reportXML; + } + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ListJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ListJSON.java new file mode 100644 index 00000000..34c2c99b --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/ListJSON.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.ArrayList; +import java.util.Map; + +import org.openecomp.portalsdk.analytics.view.ColumnHeader; + +public class ListJSON { + + private ArrayList elements; + + public ArrayList getElements() { + return elements; + } + + public void setElements(ArrayList elements) { + this.elements = elements; + } + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/MessageJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/MessageJSON.java new file mode 100644 index 00000000..d3955448 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/MessageJSON.java @@ -0,0 +1,55 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; + +import org.json.JSONObject; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.view.ColumnHeader; +import org.openecomp.portalsdk.analytics.view.DataValue; +import org.openecomp.portalsdk.analytics.xmlobj.ColFilterList; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnList; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; + +public class MessageJSON { + + private String message; + private String anyStacktrace; + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + public String getAnyStacktrace() { + return anyStacktrace; + } + public void setAnyStacktrace(String anyStacktrace) { + this.anyStacktrace = anyStacktrace; + } + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/NameBooleanJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/NameBooleanJSON.java new file mode 100644 index 00000000..7f191d93 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/NameBooleanJSON.java @@ -0,0 +1,25 @@ +package org.openecomp.portalsdk.analytics.model.definition.wizard; + +public class NameBooleanJSON { + + private String name; + private boolean selected; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public boolean isSelected() { + return selected; + } + public void setSelected(boolean selected) { + this.selected = selected; + } + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryJSON.java new file mode 100644 index 00000000..ece9a02c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryJSON.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.ArrayList; +import java.util.Map; + +import org.openecomp.portalsdk.analytics.model.definition.wizard.WizardJSON; +import org.openecomp.portalsdk.analytics.view.ColumnHeader; + +public class QueryJSON implements WizardJSON { + + private String query; + private String tabName; + private String tabId; + + + public String getTabName() { + return tabName; + } + + public void setTabName(String tabName) { + this.tabName = tabName; + } + + public String getTabId() { + return tabId; + } + + public void setTabId(String tabId) { + this.tabId = tabId; + } + + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryResultJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryResultJSON.java new file mode 100644 index 00000000..41c8bca0 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/QueryResultJSON.java @@ -0,0 +1,70 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +import java.util.ArrayList; +import java.util.Map; + +import org.openecomp.portalsdk.analytics.view.ColumnHeader; + +public class QueryResultJSON { + + private String query; + + private int totalRows; + private ArrayList reportDataColumns; + private ArrayList> reportDataRows; + + + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } + + public int getTotalRows() { + return totalRows; + } + + public void setTotalRows(int totalRows) { + this.totalRows = totalRows; + } + + public ArrayList getReportDataColumns() { + return reportDataColumns; + } + + public void setReportDataColumns(ArrayList reportDataColumns) { + this.reportDataColumns = reportDataColumns; + } + + public ArrayList> getReportDataRows() { + return reportDataRows; + } + + public void setReportDataRows(ArrayList> reportDataRows) { + this.reportDataRows = reportDataRows; + } + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/SearchFieldJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/SearchFieldJSON.java new file mode 100644 index 00000000..3689619c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/SearchFieldJSON.java @@ -0,0 +1,41 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.definition.wizard; + +public class SearchFieldJSON implements ElementJSON { + + private String id; + private String name; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/WizardJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/WizardJSON.java new file mode 100644 index 00000000..8ef937c1 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/definition/wizard/WizardJSON.java @@ -0,0 +1,9 @@ +package org.openecomp.portalsdk.analytics.model.definition.wizard; + +public interface WizardJSON { + + public String getTabName(); + public void setTabName(String tabName); + public String getTabId(); + public void setTabId(String tabId); +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PageEvent.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PageEvent.java new file mode 100644 index 00000000..c724a20a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PageEvent.java @@ -0,0 +1,256 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.pdf; + +import java.awt.Color; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; + +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.Globals; + +import com.lowagie.text.BadElementException; +import com.lowagie.text.Cell; +import com.lowagie.text.Document; +import com.lowagie.text.ExceptionConverter; +import com.lowagie.text.Font; +import com.lowagie.text.FontFactory; +import com.lowagie.text.Image; +import com.lowagie.text.Paragraph; +import com.lowagie.text.Rectangle; +import com.lowagie.text.pdf.PdfContentByte; +import com.lowagie.text.pdf.PdfDestination; +import com.lowagie.text.pdf.PdfOutline; +import com.lowagie.text.pdf.PdfPCell; +import com.lowagie.text.pdf.PdfPTable; +import com.lowagie.text.pdf.PdfPageEventHelper; +import com.lowagie.text.pdf.PdfWriter; + +class PageEvent extends PdfPageEventHelper { + private PdfBean pb; + private int pageNo = 0; + private int omit_page_count = 0; + private int DEFAULT_LOGO_SIZE = 100; + + public PageEvent(PdfBean pb) { + this.pb = pb; + } + + private int getWidthEntries(int howManyLogos){ + int widthEntries = 0; + + if(howManyLogos == 2) + widthEntries = 3; + else + if(howManyLogos == 1) + widthEntries = 2; + else + widthEntries = 0; + + return widthEntries; + } + + private int getHowManyLogos(){ + int howManyLogos = 0; + + if(AppUtils.isNotEmpty(pb.getLogo1Url()) && !pb.getLogo1Url().equalsIgnoreCase("")) + howManyLogos ++; + + if(AppUtils.isNotEmpty(pb.getLogo2Url()) && !pb.getLogo2Url().equalsIgnoreCase("")) + howManyLogos ++; + + return howManyLogos; + } + + private float[] fillWidthsArray(int howManyLogos){ + float[] widthsArray = new float[howManyLogos + 1]; + + //If one logo, we will need two columns in the header[left log, spacer] + if(howManyLogos == 1){ + widthsArray = new float[2]; + widthsArray[0] = 0.1f; + widthsArray[1] = 0.1f; + } + //If two logs, we will need three columns in the header [left log, spacer, right log] + else + if(howManyLogos == 2){ + widthsArray = new float[3]; + widthsArray[0] = 0.1f; + widthsArray[1] = 0.5f; + widthsArray[2] = 0.1f; + } + + return widthsArray; + } + public void onStartPage(PdfWriter writer, Document document) { + + Font font = FontFactory.getFont(Globals.getFooterFontFamily(), Globals.getFooterFontSize(), Font.NORMAL, Color.BLACK); + int howManyLogos = getHowManyLogos(); + + //No need to draw anything in the header if no logo was set in the report. + if(howManyLogos == 0) + return; + + float[] widths = fillWidthsArray(howManyLogos); + + PdfPTable foot = new PdfPTable(widths); + + if(AppUtils.isNotEmpty(pb.getLogo1Url()) && !pb.getLogo1Url().equalsIgnoreCase("")) + addLogo(foot, font, pb.getLogo1Url().substring(pb.getLogo1Url().indexOf("|") + 1).trim(), Cell.ALIGN_LEFT, pb.getLogo1Size() == null ? DEFAULT_LOGO_SIZE : pb.getLogo1Size()); + + PdfPCell spacingCell = new PdfPCell(); + spacingCell.setBorderColor(Color.WHITE); + foot.addCell(spacingCell); + + //Using logo1 size for now - use logo2 size if it is required to deal it separately. + if(AppUtils.isNotEmpty(pb.getLogo2Url()) && !pb.getLogo2Url().equalsIgnoreCase("")) + addLogo(foot, font, pb.getLogo2Url().substring(pb.getLogo2Url().indexOf("|") + 1).trim(), Cell.ALIGN_RIGHT, pb.getLogo2Size() == null ? DEFAULT_LOGO_SIZE : pb.getLogo2Size()); + + foot.setTotalWidth(getPageWidth(document)); + foot.writeSelectedRows(0, -1, 36, 600, writer.getDirectContent()); + } + + public void onEndPage(PdfWriter writer, Document document) { + + Font font = FontFactory.getFont(Globals.getFooterFontFamily(), Globals.getFooterFontSize(), Font.NORMAL, Color.BLACK); + + try { + + // footer + float[] f = { 1f, 0.4f, 1f }; + PdfPTable foot = new PdfPTable(f); + foot.getDefaultCell().setBorderWidth(0); + foot.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + foot.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM); + + foot.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_LEFT); + addLeftFooter(foot, font); + + foot.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + addPageNumber(foot, font, pb.isPageNumberAtFooter(), document.getPageNumber()); + + foot.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_RIGHT); + foot.getDefaultCell().setNoWrap(true); + + foot.addCell(new Paragraph(" " + PdfReportHandler.currentTime(pb.getTimestampPattern()), font)); + + foot.setTotalWidth(getPageWidth(document)); + foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); + + // bookmark + pageNo++; + PdfContentByte cb = writer.getDirectContent(); + PdfDestination destination = new PdfDestination(PdfDestination.FITH); + String bookmark = "Data Page " + (pageNo - omit_page_count); + if (pageNo == 1) { + if (pb.isCoverPageIncluded()) { + bookmark = "Cover Page"; + omit_page_count++; + } else if (pb.isDisplayChart()) { + bookmark = "Chart"; + omit_page_count++; + } + } + if (pageNo == 2 && pb.isCoverPageIncluded() && pb.isDisplayChart()) { + bookmark = "Chart"; + omit_page_count++; + } + + PdfOutline outline = new PdfOutline(cb.getRootOutline(), destination, bookmark); + + } catch (Exception e) { + throw new ExceptionConverter(e); + } + } + + private void addPageNumber(PdfPTable table, Font font, boolean isAdd, int pageNum) { + if (isAdd) + table.addCell(new Paragraph(Globals.getWordBeforePageNumber() + " " + pageNum + " " + Globals.getWordAfterPageNumber(), font)); + else + table.addCell(""); + } + + private void addLeftFooter(PdfPTable table, Font font) { + Font font1 = new Font(font); + font1.setSize(Globals.getPDFFooterFontSize()); + + if (isEmpty(pb.getLeftFooter())) + table.addCell(new Paragraph(" " + Globals.getPDFFooter(), font1)); + else + table.addCell(new Paragraph(pb.getLeftFooter(), font)); + } + + private void addHeaderDummy(PdfPTable table, Font font) { + Font font1 = new Font(font); + font1.setSize(Globals.getPDFFooterFontSize()); + + table.addCell(new Paragraph("Header row", font1)); + } + + private void addLogo(PdfPTable table, Font font, String imgSrc, int alignment, int absoluteSize) { + + Image img = null; + try { + img = Image.getInstance(pb.getFullWebContextPath() + AppUtils.getImgFolderURL() + File.separator + imgSrc); + } catch (BadElementException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + img = null; + } catch (MalformedURLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + img = null; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + + } + if(img == null){ + //log that the input file couldnt be loaded - + } + else{ + //img.scaleAbsolute(absoluteSize, absoluteSize); + img.scalePercent(absoluteSize, absoluteSize); + PdfPCell cell = new PdfPCell(img); + cell.setBorderColor(Color.WHITE); + cell.setHorizontalAlignment(alignment); + table.addCell(cell); + } + + } + + public static float getPageWidth(Document doc) { + return doc.getPageSize().width() - doc.leftMargin() - doc.rightMargin(); + } + + public static float getPageHeight(Document doc) { + return doc.getPageSize().height() - doc.topMargin() - doc.bottomMargin(); + } + + private float getHeadTopMargin(Document doc, PdfPTable table) { + return doc.getPageSize().height() - doc.topMargin() + table.getTotalHeight(); + } + + private boolean isEmpty(String str) { + return str == null || str.trim().length() == 0; + } + +} // PageEvent diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfBean.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfBean.java new file mode 100644 index 00000000..31b26435 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfBean.java @@ -0,0 +1,242 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.pdf; + + +public class PdfBean { + + public static final int NUMBER_IN_HEADER = 0; + public static final int NUMBER_IN_FOOTER = 1; + public static final int NUMBER_IN_BOTH = 2; + + private boolean alternateColor; + private boolean isPortrait; + private boolean isCoverPageIncluded; + private boolean isDisplayChart; + private int currentPage; + private int whereToShowPageNumber; + private String userId; + private String timestampPattern; + private String title; + private String leftFooter; + private String pagesize; + private boolean isAttachmentOfEmail; + private String logo1Url; + private Integer logo1Size; + private String logo2Url; + private Integer logo2Size; + private String fullWebContextPath; + + /** + * @return the leftFooter + */ + public String getLeftFooter() { + return leftFooter; + } + /** + * @param leftFooter the leftFooter to set + */ + public void setLeftFooter(String leftFooter) { + this.leftFooter = leftFooter; + } + /** + * @return the title + */ + public String getTitle() { + return title; + } + /** + * @param title the title to set + */ + public void setTitle(String title) { + this.title = title; + } + /** + * @return the alternateColor + */ + public boolean isAlternateColor() { + return alternateColor; + } + /** + * @param alternateColor the alternateColor to set + */ + public void setAlternateColor(boolean alternateColor) { + this.alternateColor = alternateColor; + } + /** + * @return the currentPage + */ + public int getCurrentPage() { + return currentPage; + } + /** + * @param currentPage the currentPage to set + */ + public void setCurrentPage(int currentPage) { + this.currentPage = currentPage; + } + /** + * @return the isPortrait + */ + public boolean isPortrait() { + return isPortrait; + } + /** + * @param isPortrait the isPortrait to set + */ + public void setPortrait(boolean isPortrait) { + this.isPortrait = isPortrait; + } + /** + * @return the timestampPattern + */ + public String getTimestampPattern() { + return timestampPattern; + } + /** + * @param timestampPattern the timestampPattern to set + */ + public void setTimestampPattern(String timestampPattern) { + this.timestampPattern = timestampPattern; + } + /** + * @return the userId + */ + public String getUserId() { + return userId; + } + /** + * @param userId the userId to set + */ + public void setUserId(String userId) { + this.userId = userId; + } + /** + * @return the whereToShowPageNummber + */ + public int getWhereToShowPageNumber() { + return whereToShowPageNumber; + } + /** + * @param whereToShowPageNumber the whereToShowPageNumber to set + */ + public void setWhereToShowPageNumber(int whereToShowPageNumber) { + this.whereToShowPageNumber = whereToShowPageNumber; + } + + public boolean isPageNumberAtHeader() { + return getWhereToShowPageNumber()==NUMBER_IN_BOTH || + getWhereToShowPageNumber()==NUMBER_IN_HEADER; + } + + public boolean isPageNumberAtFooter() { + return getWhereToShowPageNumber()==NUMBER_IN_FOOTER || + getWhereToShowPageNumber()==NUMBER_IN_BOTH; + } + + /** + * @return the isCoverPageIncluded + */ + public boolean isCoverPageIncluded() { + return isCoverPageIncluded; + } + /** + * @param isCoverPageIncluded the isCoverPageIncluded to set + */ + public void setCoverPageIncluded(boolean isCoverPageIncluded) { + this.isCoverPageIncluded = isCoverPageIncluded; + } + + public String toString() { + return getTitle()+ " " + + getCurrentPage() + " " + + getTimestampPattern() + " " + + getUserId()+ " " + + getWhereToShowPageNumber()+ " " + + isPortrait() + " " + isAlternateColor(); + } + /** + * @return the isDisplayChart + */ + public boolean isDisplayChart() { + return isDisplayChart; + } + /** + * @param isDisplayChart the isDisplayChart to set + */ + public void setDisplayChart(boolean isDisplayChart) { + this.isDisplayChart = isDisplayChart; + } + /** + * @return the pagesize + */ + public String getPagesize() { + return pagesize; + } + /** + * @param pagesize the pagesize to set + */ + public void setPagesize(String pagesize) { + this.pagesize = pagesize; + } + + public String getLogo1Url() { + return logo1Url; + } + public void setLogo1Url(String logo1Url) { + this.logo1Url = logo1Url; + } + + public String getLogo2Url() { + return logo2Url; + } + public void setLogo2Url(String logo2Url) { + this.logo2Url = logo2Url; + } + + public void setAttachmentOfEmail(boolean isAttachmentOfEmail) { + this.isAttachmentOfEmail = isAttachmentOfEmail; + } + + public boolean isAttachmentOfEmail() { + + return isAttachmentOfEmail; + } + public Integer getLogo1Size() { + return logo1Size; + } + public void setLogo1Size(Integer logo1Size) { + this.logo1Size = logo1Size; + } + public Integer getLogo2Size() { + return logo2Size; + } + public void setLogo2Size(Integer logo2Size) { + this.logo2Size = logo2Size; + } + public String getFullWebContextPath() { + return fullWebContextPath; + } + public void setFullWebContextPath(String fullWebContextPath) { + this.fullWebContextPath = fullWebContextPath; + } + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfReportHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfReportHandler.java new file mode 100644 index 00000000..c27ba0c5 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/pdf/PdfReportHandler.java @@ -0,0 +1,1898 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ + +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * PdfReportHandler.java - This class is used to generate reports in PDF using iText + * ------------------------------------------------------------------------------------------- + * + * + * Changes + * ------- + * 14-Jul-2009 : Version 8.4 (Sundar);
    + *
  • Dashboard reports can be downloaded with each report occupying separate page including its charts.
  • + *
+ * + */ +package org.openecomp.portalsdk.analytics.model.pdf; + +import java.awt.Color; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringReader; +import java.net.MalformedURLException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TimeZone; +import java.util.TreeMap; +import java.util.Vector; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.ReportSQLException; +import org.openecomp.portalsdk.analytics.model.ReportHandler; +import org.openecomp.portalsdk.analytics.model.ReportLoader; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.system.Globals; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.HtmlStripper; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.view.ColumnHeader; +import org.openecomp.portalsdk.analytics.view.ColumnHeaderRow; +import org.openecomp.portalsdk.analytics.view.DataRow; +import org.openecomp.portalsdk.analytics.view.DataValue; +import org.openecomp.portalsdk.analytics.view.HtmlFormatter; +import org.openecomp.portalsdk.analytics.view.ReportData; +import org.openecomp.portalsdk.analytics.view.RowHeader; +import org.openecomp.portalsdk.analytics.view.RowHeaderCol; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.lowagie.text.BadElementException; +import com.lowagie.text.Chunk; +import com.lowagie.text.Document; +import com.lowagie.text.DocumentException; +import com.lowagie.text.Element; +import com.lowagie.text.ElementTags; +import com.lowagie.text.Font; +import com.lowagie.text.FontFactory; +import com.lowagie.text.Image; +import com.lowagie.text.PageSize; +import com.lowagie.text.Paragraph; +import com.lowagie.text.Phrase; +import com.lowagie.text.Rectangle; +import com.lowagie.text.html.simpleparser.HTMLWorker; +import com.lowagie.text.html.simpleparser.StyleSheet; +import com.lowagie.text.pdf.PdfPCell; +import com.lowagie.text.pdf.PdfPTable; +import com.lowagie.text.pdf.PdfWriter; + +/** + * @author mwliu and sundar + * + */ +public class PdfReportHandler extends org.openecomp.portalsdk.analytics.RaptorObject{ + + /** + * + */ + private PdfBean pb; + private HtmlStripper strip = new HtmlStripper(); + private static final int RetryCreateNewImage = 3; + private int retryCreateNewImageCount=0; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PdfReportHandler.class); + + private String FONT_FAMILY = "Arial"; + private int FONT_SIZE = 9; + + public PdfReportHandler() { } + + public void createPdfFileContent(HttpServletRequest request, HttpServletResponse response, int type) throws IOException, RaptorException { + + Document document = new Document(); + ReportHandler rh = new ReportHandler(); + String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + String pdfFName = ""; + String user_id = AppUtils.getUserID(request); + response.reset(); + response.setContentType("application/pdf"); + OutputStream outStream = response.getOutputStream(); + + String formattedReportName = ""; + PdfWriter writer = null; + ReportRuntime firstReportRuntimeObj = null; + int returnValue = 0; + + ReportRuntime rr = null; + if(rr==null) rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + + boolean isDashboard = false; + if ((request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) { + isDashboard = true; + } + if(isDashboard) { + try { + String reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID); + ReportRuntime rrDash = rh.loadReportRuntime(request, reportID, true, 1); + pb = preparePdfBean(request,rrDash); + + // Setting pb Values + document.setPageSize(PageSize.getRectangle(pb.getPagesize())); + if(!pb.isPortrait()) // get this from properties file + document.setPageSize(document.getPageSize().rotate()); + + // + writer = PdfWriter.getInstance(document, response.getOutputStream()); + writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark + document.open(); + + formattedReportName = new HtmlStripper().stripSpecialCharacters(rrDash.getReportName()); + if(pb.isAttachmentOfEmail()) + response.setHeader("Content-disposition", "inline"); + else + response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf"); + + pdfFName = "dashboard"+formattedReportName+formattedDate+user_id+".pdf"; + Map reportRuntimeMap = null; + Map reportDataMap = null; + Map reportDisplayTypeMap = null; + + reportRuntimeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + reportDataMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + reportDisplayTypeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); + + if(reportRuntimeMap!=null) { + //ServletOutputStream sos = response.getOutputStream(); + Set setReportRuntime = reportRuntimeMap.entrySet(); + Set setReportDataMap = reportDataMap.entrySet(); + Set setReportDisplayTypeMap = reportDisplayTypeMap.entrySet(); + + Iterator iter2 = setReportDataMap.iterator(); + Iterator iter3 = setReportDisplayTypeMap.iterator(); + int count = 0; + for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { + count++; + Map.Entry entryData = (Entry) iter2.next(); + Map.Entry entry = (Entry) iter.next(); + Map.Entry entryCheckChart = (Entry) iter3.next(); + //String rep_id = (String) entry.getKey(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + + if(count == 1) { + firstReportRuntimeObj = (ReportRuntime) entry.getValue(); + if(pb.isCoverPageIncluded()) { + document = paintDashboardCoverPage(document, rrDash, firstReportRuntimeObj, request); + } + } + ReportData rdDashRep = (ReportData) entryData.getValue(); + int col = 0; + //pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart()); + if( ((rrDashRep.getChartType()).trim().length()>0 && rrDashRep.getDisplayChart()) && entryCheckChart.getValue().toString().equals("c")) { + document.newPage(); + pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName()); + paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rrDashRep.getReportID()+".png", rrDashRep); + } else { + document.newPage(); + pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName()); + paintPdfData(request, document,rdDashRep,rrDashRep, ""); + } + } + + } + } catch (DocumentException dex) {dex.printStackTrace();} + catch (RaptorException rex) {rex.printStackTrace();} + } else { + + //ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + //ReportData rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA); + rr = null; + ReportData rd = null; + String parent = ""; + int parentFlag = 0; + if(!nvl(request.getParameter("parent"), "").equals("N")) parent = nvl(request.getParameter("parent"), ""); + if(parent.startsWith("parent_")) parentFlag = 1; + if(parentFlag == 1) { + rr = (ReportRuntime) request.getSession().getAttribute(parent+"_rr"); + rd = (ReportData) request.getSession().getAttribute(parent+"_rd"); + } + if(rr==null) rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); + if(rd==null) rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA); + + pb = preparePdfBean(request,rr); + FONT_FAMILY = rr.getPDFFont(); + FONT_SIZE = rr.getPDFFontSize(); + //System.out.println(pb); + + formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); + + + + response.setContentType("application/pdf"); + if(pb.isAttachmentOfEmail()) + response.setHeader("Content-disposition", "inline"); + else + response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf"); + + document.setPageSize(PageSize.getRectangle(pb.getPagesize())); + + if(!pb.isPortrait()) // get this from properties file + document.setPageSize(document.getPageSize().rotate()); + + try { + + writer = PdfWriter.getInstance(document, outStream); + writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark + document.open(); + + //System.out.println("Document 1 " + document); + if(pb.isCoverPageIncluded()) { + document = paintCoverPage(document, rr, request); + } + + //boolean isImageRotate = false; + //System.out.println("Document 2 " + document); + + if(pb.isDisplayChart()) { + paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+".png", rr); + } + //System.out.println("Document 4" + document); + + document.newPage(); + if(type == 3 && rr.getSemaphoreList()==null && !(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) ) { //type = 3 is whole + String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + returnValue = paintPdfData(request, document, rd, rr, sql_whole); + } else if(type == 2) { + returnValue = paintPdfData(request, document, rd, rr, ""); + } else { + //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); + String action = request.getParameter(AppConstants.RI_ACTION); + + if(!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session")) + rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, false /*download*/); + if(rr.getSemaphoreList()!=null) { + rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, true); + returnValue = paintPdfData(request, document, rd, rr, ""); + } else { + returnValue = paintPdfData(request, document, rd, rr, rr.getWholeSQL()); + } + + + } + + + //paintPdfData(document,rd,rr); + + + } catch (DocumentException de) { + de.printStackTrace(); + //System.err.println("document: " + de.getMessage()); + } + + } + document.close(); + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + + } + + private Document paintCoverPage(Document doc, ReportRuntime rr, HttpServletRequest request) throws IOException, DocumentException { + + //System.out.println("PDFREPORTHANDLER STARTED ... " ); + if(nvl(rr.getPdfImg()).length()>0) { + Image image1 = Image.getInstance(AppUtils.getExcelTemplatePath()+"../../"+AppUtils.getImgFolderURL()+rr.getPdfImg()); + image1.scalePercent(20f, 20f); + doc.add(image1); + } + float firstColumnSize = Globals.getCoverPageFirstColumnSize(); + float[] relativeWidths = {firstColumnSize,1f-firstColumnSize}; + PdfPTable table = new PdfPTable(relativeWidths); + table.getDefaultCell().setBorderWidth(0); + addEmptyRows(table,6); + HTMLWorker worker = new HTMLWorker(doc); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("body", "leading", "16,0"); + StringBuffer reportDescrBuf = new StringBuffer(""); + ArrayList descr = HTMLWorker.parseToList(new StringReader(nvl(rr.getReportDescr())), style); + ArrayList paraList = null; + if(nvl(rr.getReportTitle()).length()>0) { + add2Cells(table,"Report Title : ",nvl(rr.getReportTitle())); + if(nvl(rr.getReportSubTitle()).length()>0) { + add2Cells(table,"Report Sub-Title : ",nvl(rr.getReportSubTitle())); + System.out.println("Adding the report sub-title "); + } + + } else { + add2Cells(table,"Report Name : ",nvl(rr.getReportName())); + } + if((descr!=null && descr.size()>0)) { + paraList = (com.lowagie.text.Paragraph)descr.get(0); + for (int i=0 ; i0) { + String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(","); + String name=nameValue[0]; + String value=nameValue[1]; + add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value)))); + } + + if(Globals.isCreatedOwnerInfoNeeded()) { + add2Cells(table,"Created By : ",nvl(AppUtils.getUserName(rr.getCreateID()))); + add2Cells(table,"Owner : ",nvl(AppUtils.getUserName(rr.getOwnerID()))); + } + if(Globals.displayLoginIdForDownloadedBy()) + add2Cells(table,"Downloaded by : ",nvl(AppUtils.getUserBackdoorLoginId(request))); + else + add2Cells(table,"Downloaded by : ",nvl(AppUtils.getUserName(AppUtils.getUserID(request)))); + + addEmptyRows(table,1); + + boolean isFirstRow = true; + ArrayList al = rr.getParamNameValuePairsforPDFExcel(request, 1); + if(al.size()<=0) { + al = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + } + + Iterator it = al.iterator(); + addEmptyRows(table,1); + //if(!Globals.customizeFormFieldInfo()) { + if(rr.getFormFieldComments(request).length()<=0) { + while(it.hasNext()) { + + if(isFirstRow) { + add2Cells(table, "Run-time Criteria : ", " "); + isFirstRow = false; + } + + IdNameValue value = (IdNameValue)it.next(); + if(!value.getId().trim().equals("BLANK")) + //System.out.println("PDFREPORTHANDLER " + value.getId()+" : "+value.getName()); + add2Cells(table, value.getId()+" : ",value.getName().replaceAll("~",",")); + //add2Cells(table, rr.getFormFieldComments(request), " "); + } + addEmptyRows(table,1); + doc.add(table); + + } else { + it = al.iterator(); + if(it.hasNext()) { + //add2Cells(table, "Run-time Criteria : ", " "); + addEmptyRows(table,1); + doc.add(table); + //com.lowagie.text.html.HtmlParser.parse(doc, new StringReader(rr.getFormFieldComments(request))); + ArrayList p = HTMLWorker.parseToList(new StringReader(rr.getFormFieldComments(request).replaceAll("~",",")), style); + + for (int k = 0; k < p.size(); ++k){ + doc.add((com.lowagie.text.Element)p.get(k)); + } + } + } + + return doc; + } + + + private Document paintDashboardCoverPage(Document doc, ReportRuntime rrDashRep, ReportRuntime firstReportRuntimeObj, HttpServletRequest request) throws IOException, DocumentException { + + //System.out.println("PDFREPORTHANDLER STARTED ... " ); + float firstColumnSize = Globals.getCoverPageFirstColumnSize(); + float[] relativeWidths = {firstColumnSize,1f-firstColumnSize}; + PdfPTable table = new PdfPTable(relativeWidths); + table.getDefaultCell().setBorderWidth(0); + addEmptyRows(table,6); + + add2Cells(table,"Report Name : ",rrDashRep.getReportName()); + add2Cells(table,"Description : ",rrDashRep.getReportDescr()); + if(Globals.getSessionInfoForTheCoverPage().length()>0) { + String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(","); + String name=nameValue[0]; + String value=nameValue[1]; + add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value)))); + } + + if(Globals.isCreatedOwnerInfoNeeded()) { + add2Cells(table,"Created By : ",AppUtils.getUserName(rrDashRep.getCreateID())); + add2Cells(table,"Owner : ",AppUtils.getUserName(rrDashRep.getOwnerID())); + } + if(Globals.displayLoginIdForDownloadedBy()) + add2Cells(table,"Downloaded by : ",AppUtils.getUserBackdoorLoginId(request)); + else + add2Cells(table,"Downloaded by : ",AppUtils.getUserName(request)); + + addEmptyRows(table,1); + + boolean isFirstRow = true; + ArrayList al = firstReportRuntimeObj.getParamNameValuePairsforPDFExcel(request, 2); + Iterator it = al.iterator(); + addEmptyRows(table,1); + //if(!Globals.customizeFormFieldInfo()) { + if(firstReportRuntimeObj.getFormFieldComments(request).length()<=0) { + while(it.hasNext()) { + + if(isFirstRow) { + add2Cells(table, "Run-time Criteria : ", " "); + isFirstRow = false; + } + + IdNameValue value = (IdNameValue)it.next(); + if(!value.getId().trim().equals("BLANK")) + //System.out.println("PDFREPORTHANDLER " + value.getId()+" : "+value.getName()); + add2Cells(table, value.getId()+" : ",value.getName()); + //add2Cells(table, rr.getFormFieldComments(request), " "); + } + addEmptyRows(table,1); + doc.add(table); + + } else { + it = al.iterator(); + if(it.hasNext()) { + //add2Cells(table, "Run-time Criteria : ", " "); + addEmptyRows(table,1); + doc.add(table); + //com.lowagie.text.html.HtmlParser.parse(doc, new StringReader(rr.getFormFieldComments(request))); + HTMLWorker worker = new HTMLWorker(doc); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("body", "leading", "16,0"); + ArrayList p = HTMLWorker.parseToList(new StringReader(firstReportRuntimeObj.getFormFieldComments(request)), style); + + for (int k = 0; k < p.size(); ++k){ + doc.add((com.lowagie.text.Element)p.get(k)); + } + } + } + + return doc; + } + + + public static void addEmptyRows(PdfPTable table, int rows) throws DocumentException { + for (int i=0; i0?AppUtils.getRequestNvlValue(request, "multiplePieOrder").equals("row"):rr.isMultiplePieOrderByRow())) ); + additionalChartOptionsMap.put("multiplePieLabelDisplay", AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay").length()>0? AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"):rr.getMultiplePieLabelDisplay()); + additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D())); + } else if (chartType.equals(AppConstants.GT_BAR_3D)) { + additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) ); + additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer()); + additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D())); + additionalChartOptionsMap.put("lastSeriesALineChart", new Boolean(rr.isLastSeriesALineChart())); + } else if (chartType.equals(AppConstants.GT_LINE)) { + additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) ); + //additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer()); + additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D())); + additionalChartOptionsMap.put("lastSeriesABarChart", new Boolean(rr.isLastSeriesABarChart())); + } else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) { + additionalChartOptionsMap.put("intervalFromDate",AppUtils.getRequestNvlValue(request, "intervalFromDate").length()>0?AppUtils.getRequestNvlValue(request, "intervalFromDate"):rr.getIntervalFromdate()); + additionalChartOptionsMap.put("intervalToDate", AppUtils.getRequestNvlValue(request, "intervalToDate").length()>0? AppUtils.getRequestNvlValue(request, "intervalToDate"):rr.getIntervalTodate()); + additionalChartOptionsMap.put("intervalLabel", AppUtils.getRequestNvlValue(request, "intervalLabel").length()>0? AppUtils.getRequestNvlValue(request, "intervalLabel"):rr.getIntervalLabel()); + } else if (chartType.equals(AppConstants.GT_REGRESSION)) { + additionalChartOptionsMap.put("regressionType",AppUtils.getRequestNvlValue(request, "regressionType").length()>0?AppUtils.getRequestNvlValue(request, "regressionType"):rr.getLinearRegression()); + additionalChartOptionsMap.put("linearRegressionColor",nvl(rr.getLinearRegressionColor())); + additionalChartOptionsMap.put("expRegressionColor",nvl(rr.getExponentialRegressionColor())); + additionalChartOptionsMap.put("maxRegression",nvl(rr.getCustomizedRegressionPoint())); + } else if (chartType.equals(AppConstants.GT_STACK_BAR) ||chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES) + || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES) + ) { + additionalChartOptionsMap.put("overlayItemValue",new Boolean(nvl(rr.getOverlayItemValueOnStackBar()).equals("Y"))); + } + additionalChartOptionsMap.put("legendPosition", nvl(rr.getLegendPosition())); + additionalChartOptionsMap.put("hideToolTips", new Boolean(rr.hideChartToolTips())); + additionalChartOptionsMap.put("hideLegend", new Boolean(AppUtils.getRequestNvlValue(request, "hideLegend").length()>0? AppUtils.getRequestNvlValue(request, "hideLegend").equals("Y"):rr.hideChartLegend())); + additionalChartOptionsMap.put("labelAngle", nvl(rr.getLegendLabelAngle())); + additionalChartOptionsMap.put("maxLabelsInDomainAxis", nvl(rr.getMaxLabelsInDomainAxis())); + additionalChartOptionsMap.put("rangeAxisLowerLimit", nvl(rr.getRangeAxisLowerLimit())); + additionalChartOptionsMap.put("rangeAxisUpperLimit", nvl(rr.getRangeAxisUpperLimit())); + + + boolean totalOnChart = false; + totalOnChart = AppUtils.getRequestNvlValue(request, "totalOnChart").equals("Y"); + String filename = null; + ArrayList graphURL = new ArrayList(); + ArrayList chartNames = new ArrayList(); + ArrayList fileNames = new ArrayList(); + List l = rr.getAllColumns(); + List lGroups = rr.getAllChartGroups(); + HashMap mapYAxis = rr.getAllChartYAxis(rr.getReportParamValues()); + String chartLeftAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartLeftAxisLabel())); + String chartRightAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartRightAxisLabel())); + int displayTotalOnChart = 0; + HashMap formValues = Globals.getRequestParamtersMap(request, false); + + for (Iterator iterC = l.iterator(); iterC.hasNext();) { + DataColumnType dc = (DataColumnType) iterC.next(); + if(nvl(dc.getColName()).equals(AppConstants.RI_CHART_TOTAL_COL)) { + displayTotalOnChart = 1; + } + } + + String legendColumnName = (rr.getChartLegendColumn()!=null)?rr.getChartLegendColumn().getDisplayName():"Legend Column"; + + + + if(ds!=null) + { + if(rr.hasSeriesColumn() && chartType.equals(AppConstants.GT_TIME_SERIES) && (lGroups==null || lGroups.size() <= 0)) { /** Check whether Report has only category columns if so then all the columns will open in seperate chart - sundar**/ + for (int i=0; i0) + tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|")); + if(i>0) tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|")); + //System.out.println("TEMPCHARTGROUP " + tempChartGroupCurrent + " " + tempChartGroupPrev); + if(tempChartGroupCurrent.equals(tempChartGroupPrev)) continue; + //System.out.println("CHARTGROUPORG " + chartGroupOrg + " " + lGroups) ; + //String chartGroup = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|")); + String chartGroup = chartGroupOrg; + + //System.out.println("$$$$CHARTGROUP in JSP " +chartGroup+ " "+ chartGroupOrg ); + //System.out.println(" rr.getChartGroupDisplayNamesList(chartGroup) " + rr.getChartGroupDisplayNamesList(chartGroup)); + //System.out.println(" rr.getChartGroupColumnColorsList(chartGroup) " + rr.getChartGroupColumnColorsList(chartGroup)); + //System.out.println(" rr.getChartGroupColumnAxisList(chartGroup) " + rr.getChartGroupColumnAxisList(chartGroup)); + //System.out.println(" rr.getChartGroupValueColumnAxisList(chartGroupOrg) " + rr.getChartGroupValueColumnAxisList(chartGroupOrg)); + + downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png"; + String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):""); + chartTitle = rr.getFormFieldFilled(chartTitle); + String leftAxisLabel = ""; + //if(!rr.isChartMultiSeries()) { + if(!rr.isMultiSeries()) { + leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel ); + } else { + leftAxisLabel = chartLeftAxisLabel; + } + + filename = null;/*(String) ChartGen.generateChart( chartType, + request.getSession(), + ds, + legendColumnName, + leftAxisLabel, + chartRightAxisLabel, + ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupDisplayNamesList(chartGroup, formValues)), + ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupColumnColorsList(chartGroup, formValues)), + ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupValueColumnAxisList(chartGroupOrg, formValues)), + "", + chartTitle, + null, + rr.getChartWidthAsInt(), + rr.getChartHeightAsInt(), + ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues):rr.getChartGroupValueColumnAxisList(chartGroupOrg, formValues)), + rr.hasSeriesColumn(), + //rr.isChartMultiSeries(), + rr.isMultiSeries(), + rr.getAllColumns(), + downloadFileName, + totalOnChart, + AppConstants.WEB_VERSION deviceType, + additionalChartOptionsMap, + true + );*/ + try { + Image image = Image.getInstance(downloadFileName); + images.add(image); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + catch (BadElementException e) { + e.printStackTrace(); + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) { + for (int i=0; i 0))) { + + if(/*chartType.equals(AppConstants.GT_TIME_SERIES) && */rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues)!=null && rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues).size()>0) { + downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_All.png"; + String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():""; + chartTitle = rr.getFormFieldFilled(chartTitle); + + filename = null; /*(String) ChartGen.generateChart( chartType, + request.getSession(), + ds, + legendColumnName, + chartLeftAxisLabel, + chartRightAxisLabel, + rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), + rr.getChartColumnColorsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), + rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), + "", + chartTitle, + null, + rr.getChartWidthAsInt(), + rr.getChartHeightAsInt(), + rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), + rr.hasSeriesColumn(), + //rr.isChartMultiSeries(), + rr.isMultiSeries(), + rr.getAllColumns(), + downloadFileName, + totalOnChart, + AppConstants.WEB_VERSION, + additionalChartOptionsMap, + true + );*/ + try { + Image image = Image.getInstance(downloadFileName); + images.add(image); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + catch (BadElementException e) { + e.printStackTrace(); + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } // Stacked Chart Check + } // else no Series Column + + }// if(ds!=null) + + }catch (Exception e) { + e.printStackTrace(); + } +// System.out.println("Total Images " + images.size()); + return images.size()>0?images:null; + + } + +/* + private boolean isImageRotate(Document doc, Image image) { + + System.out.println("image size="+image.getWidthPercentage()+ " "+ image.scaledWidth()+ + " "+image.scaledHeight()+" "+image.getXYRatio()); + System.out.println("page size = "+ doc.getPageSize().width() + " " +doc.getPageSize().height() +" "+ + doc.topMargin() + " " +doc.bottomMargin() + " " + doc.leftMargin() + " " + + doc.rightMargin()); + System.out.println(image.scaledWidth()/image.scaledHeight()); + System.out.println((PageEvent.getPageWidth(doc)/PageEvent.getPageHeight(doc))); +// System.out.println(doc.getPageSize().getRotation()); + + float image_w = image.scaledWidth(); + float image_h = image.scaledHeight(); + float image_ratio = image_w/image_h; + + float page_w = PageEvent.getPageWidth(doc); + float page_h = PageEvent.getPageHeight(doc); + float page_ratio = page_w/page_h; + + return (image_w > page_w && image_ratio > page_ratio) || + (image_h > page_h && image_ratio < page_ratio); + + } + +*/ + private final int DEFAULT_PDF_DISPLAY_WIDTH = 10; + private int paintPdfData(HttpServletRequest request, Document document, ReportData rd, ReportRuntime rr, String sql_whole) throws DocumentException, RaptorException, IOException { + + int mb = 1024*1024; + Runtime runtime = Runtime.getRuntime(); + int returnValue = 0; + //sql_whole = rr.getWholeSQL(); + //if(rd.getDataRowCount() >= rr.getReportDataSize()) { + //sql_whole=""; + //} + float f[] = getRelativeWidths(rd, rr.getReportType().equals(AppConstants.RT_CROSSTAB)); + PdfPTable table = new PdfPTable(f); + table.setWidthPercentage(100f); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM); + + ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, rr.getReportID()); + + List allColumns = rdef.getAllColumns(); + + float[] repotWidths = new float[rdef.getVisibleColumnCount()]; + int columnIdx = 0; + float pdfDisplayWidth = 0; + for(Iterator iter = allColumns.iterator(); iter.hasNext();){ + DataColumnType dct = (DataColumnType) iter.next(); + if(dct.isVisible()) { + + if(dct.getPdfDisplayWidthInPxls() == null || dct.getPdfDisplayWidthInPxls().equals("") || dct.getPdfDisplayWidthInPxls().startsWith("null")) + pdfDisplayWidth = DEFAULT_PDF_DISPLAY_WIDTH; + else + pdfDisplayWidth = Float.parseFloat(dct.getPdfDisplayWidthInPxls()); + + repotWidths [columnIdx++] = pdfDisplayWidth; + } + } + + table.setWidths(repotWidths); + + //table.setH + + //TODO: check title and subtitle + HttpSession session = request.getSession(); + String drilldown_index = (String) session.getAttribute("drilldown_index"); + int index = 0; + try { + index = Integer.parseInt(drilldown_index); + } catch (NumberFormatException ex) { + index = 0; + } + String titleRep = (String) session.getAttribute("TITLE_"+index); + String subtitle = (String) session.getAttribute("SUBTITLE_"+index); + + if(nvl(titleRep).length()>0 && nvl(subtitle).length()>0) + table.setHeaderRows(3); + else if (nvl(titleRep).length()>0) + table.setHeaderRows(2); + else + table.setHeaderRows(1); + table = paintPdfReportHeader(request, document, table, rr, f); + paintPdfTableHeader(document, rd, table); + + int idx = 0; + int fragmentsize = 30; //for memory management + + ResultSet rs = null; + Connection conn = null; + Statement st = null; + ResultSetMetaData rsmd = null; + rd.reportDataRows.resetNext(); + DataRow dr = rd.reportDataRows.getNext(); + + //addRowHeader(table,dr,idx,rd); + + //addRowColumns(table,dr,idx); + if(nvl(sql_whole).length() >0 && rr.getReportType().equals(AppConstants.RT_LINEAR)) { + try { + conn = ConnectionUtils.getConnection(rr.getDbInfo()); + st = conn.createStatement(); + logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************")); + logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole)); + logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************")); + rs = st.executeQuery(sql_whole); + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + dr = null; + int j = 0; + int rowCount = 0; + String title = ""; + while(rs.next()) { + +/* if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { + returnValue = 1; + String cellValue = Globals.getUserDefinedMessageForMemoryLimitReached() + " "+ rowCount +" records out of " + rr.getReportDataSize() + " were downloaded to PDF."; + Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), + Globals.getDataFontSize(), + Font.NORMAL, Color.BLACK); + PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + table.addCell(cell); + document.add(table); + return returnValue; + } +*/ rowCount++; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i)); + } + rd.reportDataRows.resetNext(); + + dr = rd.reportDataRows.getNext(); + + j = 0; + /*if(rd.reportTotalRowHeaderCols!=null) { + + HtmlFormatter rfmt = dr.getRowFormatter(); + + Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), + Globals.getDataFontSize(), + Font.NORMAL, Color.BLACK); + if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + + String cellValue = new Integer(rowCount).toString(); + PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + + //row background color can be overwritten by cell background color + cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + if(rfmt != null) { + formatterCell(rfmt,cell); + } + table.addCell(cell); + }*/ + + for (dr.resetNext(); dr.hasNext();j++) { + DataValue dv = dr.getNext(); + /*if(j == 0) { + HtmlFormatter cfmt = dv.getCellFormatter(); + HtmlFormatter rfmt = dv.getRowFormatter(); + + Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), + Globals.getDataFontSize(), + Font.NORMAL, Color.BLACK); + if(cfmt!= null) { + cellFormatterFont(cfmt,cellFont); + } + else if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + else { + if(dv.isBold()) { + cellFont.setStyle(Font.BOLD); + } + } + + //String cellValue = strip.stripHtml(value.trim()); + PdfPCell cell = new PdfPCell(new Paragraph(rowCount+"",cellFont)); + + //row background color can be overwritten by cell background color + cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + if(nvl(dv.getAlignment()).trim().length()>0) + cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment())); + else + cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + if(cfmt!= null) { + formatterCell(cfmt,cell); + } + else if(rfmt != null) { + formatterCell(rfmt,cell); + } + table.addCell(cell); + }*/ + + //for (chr.resetNext(); chr.hasNext();) { + //ColumnHeader ch = chr.getNext(); + String value = nvl((String)colHash.get(dv.getColId().toUpperCase())); + if(dv.isVisible()) { + + HtmlFormatter cfmt = dv.getCellFormatter(); + HtmlFormatter rfmt = dv.getRowFormatter(); + + Font cellFont = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE, + Font.NORMAL, Color.BLACK); + if(cfmt!= null) { + cellFormatterFont(cfmt,cellFont); + } + else if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + else { + if(dv.isBold()) { + cellFont.setStyle(Font.BOLD); + } + } + + String cellValue = strip.stripHtml(value.trim()); + PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + + //row background color can be overwritten by cell background color + cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + if(nvl(dv.getAlignment()).trim().length()>0) + cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment())); + else + cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + if(cfmt!= null) { + formatterCell(cfmt,cell); + } + else if(rfmt != null) { + formatterCell(rfmt,cell); + } + + + + table.addCell(cell); + + }//if isVisible() + + + } + + } + if(rd.reportDataTotalRow!=null) { + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();idx++) { + dr = rd.reportDataTotalRow.getNext(); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE, + Font.NORMAL, Color.BLACK); + rowHeaderFont.setStyle(Font.BOLD); + rowHeaderFont.setSize(FONT_SIZE+1f); + table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx)); + table.addCell(new Paragraph("Total",rowHeaderFont)); + + + addTotalRowColumns(table,dr,idx); + if (idx % fragmentsize == fragmentsize - 1) { + document.add(table); + table.deleteBodyRows(); + table.setSkipFirstHeader(true); + } + + } + } + } catch (SQLException ex) { + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + if(!(ex.getCause() instanceof java.net.SocketException) ) + throw new RaptorException (ex); + } finally { + try { + if(conn!=null) + conn.close(); + if(st!=null) + st.close(); + if(rs!=null) + rs.close(); + } catch (SQLException ex) { + throw new RaptorException(ex); + } + } + + +// if (idx % fragmentsize == fragmentsize - 1) { +// document.add(table); +// table.deleteBodyRows(); +// table.setSkipFirstHeader(true); +// } + + //document.add(table); + } else { + if(rr.getReportType().equals(AppConstants.RT_LINEAR)) { + int rowCount = 0; + for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();idx++) + { + rowCount++; + + /*if(rd.reportTotalRowHeaderCols!=null) { + HtmlFormatter rfmt = dr.getRowFormatter(); + + Font cellFont = FontFactory.getFont(Globals.getDataFontFamily(), + Globals.getDataFontSize(), + Font.NORMAL, Color.BLACK); + if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + + //String cellValue = new Integer(rowCount).toString(); + //PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + + //row background color can be overwritten by cell background color + //cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + //cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + //if(rfmt != null) { + //formatterCell(rfmt,cell); + //} + //table.addCell(cell); + }*/ + + + + if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { + returnValue = 1; + } + + dr = rd.reportDataRows.getNext(); + + addRowHeader(table,dr,idx,rd); + + addRowColumns(table,dr,idx); + + if (idx % fragmentsize == fragmentsize - 1) { + document.add(table); + table.deleteBodyRows(); + table.setSkipFirstHeader(true); + } + } + + if(rd.reportDataTotalRow!=null) { + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();idx++) { + dr = rd.reportDataTotalRow.getNext(); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE, + Font.NORMAL, Color.BLACK); + rowHeaderFont.setStyle(Font.BOLD); + rowHeaderFont.setSize(FONT_SIZE+1f); + table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx)); + table.addCell(new Paragraph("Total",rowHeaderFont)); + + + addTotalRowColumns(table,dr,idx); + if (idx % fragmentsize == fragmentsize - 1) { + document.add(table); + table.deleteBodyRows(); + table.setSkipFirstHeader(true); + } + + } + } + + } else if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + int rowCount = 0; + List l = rd.getReportDataList(); + boolean first = true; + for (int dataRow = 0; dataRow < l.size(); dataRow++) { + first = true; + rowCount++; + dr = (DataRow) l.get(dataRow); + Vector rowNames = dr.getRowValues(); + for(dr.resetNext(); dr.hasNext(); ) { + + if(first) { + HtmlFormatter rfmt = dr.getRowFormatter(); + + Font cellFont = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE, + Font.NORMAL, Color.BLACK); + if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + String cellValue = ""; + PdfPCell cell = null; + //String cellValue = new Integer(rowCount).toString(); + //PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + //row background color can be overwritten by cell background color + //cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + //cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + //if(rfmt != null) { + //formatterCell(rfmt,cell); + // } + //table.addCell(cell); + if(rowNames!=null) { + for(int i=0; i0) { + table.getDefaultCell().setColspan(rh.getColSpan()); + table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx)); + table.addCell(new Paragraph(strip.stripHtml(rh.getRowTitle()),rowHeaderFont)); + } + } + } + + private void addRowColumns(PdfPTable table, DataRow dr, int idx) { + + table.getDefaultCell().setColspan(1); + + for(dr.resetNext();dr.hasNext();) + { + DataValue dv = dr.getNext(); + //System.out.println(columnCount +" --> "+dv); + if(dv.isVisible()) { + HtmlFormatter cfmt = dv.getCellFormatter(); + HtmlFormatter rfmt = dv.getRowFormatter(); + + Font cellFont = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE, + Font.NORMAL, Color.BLACK); + if(cfmt!= null) { + cellFormatterFont(cfmt,cellFont); + } + else if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + else { + if(dv.isBold()) { + cellFont.setStyle(Font.BOLD); + } + } + + String cellValue = strip.stripHtml(dv.getDisplayValue().trim()); + PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + + //row background color can be overwritten by cell background color + cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + if(nvl(dv.getAlignment()).trim().length()>0) + cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment())); + else + cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + if(cfmt!= null) { + formatterCell(cfmt,cell); + } + else if(rfmt != null) { + formatterCell(rfmt,cell); + } + + table.addCell(cell); + + }//if isVisible() + } + } + + + private void addTotalRowColumns(PdfPTable table, DataRow dr, int idx) { + + table.getDefaultCell().setColspan(1); + dr.resetNext(); + dr.getNext(); + for(;dr.hasNext();) + { + DataValue dv = dr.getNext(); + //System.out.println(columnCount +" --> "+dv); + if(dv.isVisible()) { + HtmlFormatter cfmt = dv.getCellFormatter(); + HtmlFormatter rfmt = dv.getRowFormatter(); + + Font cellFont = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE, + Font.NORMAL, Color.BLACK); + if(cfmt!= null) { + cellFormatterFont(cfmt,cellFont); + } + else if(rfmt != null) { + cellFormatterFont(rfmt,cellFont); + } + else { + if(dv.isBold()) { + cellFont.setStyle(Font.BOLD); + } + } + + String cellValue = strip.stripHtml(dv.getDisplayValue().trim()); + PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont)); + + //row background color can be overwritten by cell background color + cell.setBackgroundColor(getRowBackgroundColor(dr, idx)); + + if(nvl(dv.getAlignment()).trim().length()>0) + cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment())); + else + cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER); + + if(cfmt!= null) { + formatterCell(cfmt,cell); + } + else if(rfmt != null) { + formatterCell(rfmt,cell); + } + + table.addCell(cell); + + }//if isVisible() + } + } + + + private void formatterCell(HtmlFormatter fmt, PdfPCell cell) { + + if(nvl(fmt.getBgColor()).trim().length()>0) + cell.setBackgroundColor(Color.decode(fmt.getBgColor())); + if(nvl(fmt.getAlignment()).trim().length()>0) + cell.setHorizontalAlignment(ElementTags.alignmentValue(fmt.getAlignment())); + } + + private void cellFormatterFont(HtmlFormatter fmt, Font font) { + + if(fmt.isBold()) + font.setStyle(Font.BOLD); + if(fmt.isItalic()) + font.setStyle(Font.ITALIC); + if(fmt.isUnderline()) + font.setStyle(Font.UNDERLINE); + if(fmt.getFontColor().trim().length()>0) + font.setColor(Color.decode(fmt.getFontColor())); + if(fmt.getFontSize().trim().length()>0) + font.setSize(Float.parseFloat(fmt.getFontSize())-Globals.getDataFontSizeOffset()); +// if(fmt.getFontFace().trim().length()>0) +// cellFont.setFamily() + + } + + private Color getRowBackgroundColor(DataRow dr, int idx) { + + Color color = Color.decode(Globals.getDataDefaultBackgroundHexCode()); + + HtmlFormatter rhf = dr.getRowFormatter(); + if(rhf!=null && nvl(rhf.getBgColor()).trim().length()>0) + + color = Color.decode(rhf.getBgColor()); + + else if(pb.isAlternateColor() && idx%2==0) + + color = Color.decode(Globals.getDataBackgroundAlternateHexCode()); + + return color; + + } + + private int getTotalVisbleColumns(ReportData rd) { + + int totalVisbleColumn = rd.getTotalColumnCount(); + for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();) + { + DataRow dr = rd.reportDataRows.getNext(); + for(dr.resetNext();dr.hasNext();) { + DataValue dv = dr.getNext(); + if(!dv.isVisible()) totalVisbleColumn--; + } + + break; + } + + return totalVisbleColumn; + } + + /* + private int getFirstRowIndex(ReportRuntime rr) { + return (pb.getCurrentPage()>0)?pb.getCurrentPage()*rr.getPageSize()+1 : 1; + } + */ + private float[] getRelativeWidths(ReportData rd, boolean crosstab){ + + int totalColumns = getTotalVisbleColumns(rd); + /*if(rd.reportTotalRowHeaderCols!=null) { + totalColumns += 1; + }*/ + if(crosstab) { + totalColumns += 1; + } + + if(totalColumns == 0 ) + totalColumns=1; + + float[] relativeWidths = new float[totalColumns]; + //initial widths are even + for(int i=0; i0) { + //PdfPTable table = new PdfPTable(1); + table.setWidthPercentage(100f); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM); + + + Font font = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE-2f, + Font.BOLD, + Color.BLACK); + + //addEmptyRows(table,1); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor())); + title = Utils.replaceInString(title, "
", " "); + title = Utils.replaceInString(title, "
", " "); + title = Utils.replaceInString(title, "
", " "); + title = strip.stripHtml(nvl(title).trim()); + //subtitle = Utils.replaceInString(subtitle, "
", " "); + //subtitle = Utils.replaceInString(subtitle, "
", " "); + //subtitle = Utils.replaceInString(subtitle, "
", " "); + //subtitle = strip.stripHtml(nvl(subtitle).trim()); + StyleSheet styles = new StyleSheet(); + + HTMLWorker htmlWorker = new HTMLWorker(document); + ArrayList cc = new ArrayList(); + cc = htmlWorker.parseToList(new StringReader(subtitle), styles); + + Phrase p1 = new Phrase(); + for (int i = 0; i < cc.size(); i++){ + Element elem = (Element)cc.get(i); + ArrayList al = elem.getChunks(); + for (int j = 0; j < al.size(); j++) { + Chunk chunk = (Chunk) al.get(j); + chunk.font().setSize(6.0f); + } + p1.add(elem); + } + //cell = new PdfPCell(p1); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("font", "font-size", "3"); + style.loadTagStyle("font", "size", "3"); + styles.loadStyle("pdfFont1", "size", "11px"); + styles.loadStyle("pdfFont1", "font-size", "11px"); + /*ArrayList p = HTMLWorker.parseToList(new StringReader(nvl(title)), style); + for (int k = 0; k < p.size(); ++k){ + document.add((com.lowagie.text.Element)p.get(k)); + }*/ + //p1.font().setSize(3.0f); + PdfPCell titleCell = new PdfPCell(new Phrase(title, font)); + titleCell.setColspan(rr.getVisibleColumnCount()); + PdfPCell subtitleCell = new PdfPCell(p1); + subtitleCell.setColspan(rr.getVisibleColumnCount()); + titleCell.setHorizontalAlignment(1); + subtitleCell.setHorizontalAlignment(1); + table.addCell(titleCell); + table.addCell(subtitleCell); + //document.add(table); + } + return table; + } + + + private void paintPdfReportFooter(HttpServletRequest request, Document document, ReportRuntime rr, float[] f) + throws DocumentException, IOException { + + HttpSession session = request.getSession(); + String drilldown_index = (String) session.getAttribute("drilldown_index"); + int index = 0; + try { + index = Integer.parseInt(drilldown_index); + } catch (NumberFormatException ex) { + index = 0; + } + + String title = (String) session.getAttribute("FOOTER_"+index); + if(nvl(title).length()>0) { + PdfPTable table = new PdfPTable(1); + table.setWidthPercentage(100f); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM); + + Font font = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE-3f, + Font.BOLD, + Color.BLACK); + + + //addEmptyRows(table,1); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor())); + /*title = Utils.replaceInString(title, "
", " "); + title = Utils.replaceInString(title, "
", " "); + title = Utils.replaceInString(title, "
", " "); + title = strip.stripHtml(nvl(title).trim());*/ + StyleSheet style = new StyleSheet(); + + HTMLWorker htmlWorker = new HTMLWorker(document); + ArrayList cc = new ArrayList(); + cc = htmlWorker.parseToList(new StringReader(title), style); + + Phrase p1 = new Phrase(); + for (int i = 0; i < cc.size(); i++){ + Element elem = (Element)cc.get(i); + ArrayList al = elem.getChunks(); + for (int j = 0; j < al.size(); j++) { + Chunk chunk = (Chunk) al.get(j); + chunk.font().setSize(6.0f); + } + p1.add(elem); + } + +/* + HTMLWorker.parseToList(new StringReader(nvl(title)), style);*/ + PdfPCell titleCell = new PdfPCell(p1); + titleCell.setHorizontalAlignment(Element.ALIGN_LEFT); + table.addCell(titleCell); + //table. + document.add(table); + } + //return table; + } + + + private void paintPdfTableHeader(Document document, ReportData rd, PdfPTable table) + throws DocumentException { + + Font font = FontFactory.getFont(FONT_FAMILY, + FONT_SIZE+1f, + Font.BOLD, + Color.decode(Globals.getDataTableHeaderFontColor())); + //table.setHeaderRows(1); + table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); + table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor())); + String title = ""; + + boolean firstPass = true; + + /*if(rd.reportTotalRowHeaderCols!=null) { + if(firstPass) { + table.addCell(new Paragraph("No.", font)); + firstPass = false; + } + }*/ + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) + { + if(firstPass) { + for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) { + /*if(firstPass) { + table.addCell(new Paragraph("No.", font)); + firstPass = false; + } else {*/ + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + title = rhc.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + table.addCell(new Paragraph(title,font)); + //} + } + } + + ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext(); + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + //System.out.println(ch); + if(ch.isVisible()) { + title = ch.getColumnTitle(); + title = Utils.replaceInString(title,"_nl_", " \n"); + table.addCell(new Paragraph(title,font)); + } + } + } + } + + public static String currentTime(String pattern) { + try { + SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); + Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); + SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); + return dtimestamp.format(sysdate)+" "+Globals.getTimeZone(); + //paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone())); + } catch(Exception ex) {} + + SimpleDateFormat s = new SimpleDateFormat(pattern); + s.setTimeZone(TimeZone.getTimeZone(Globals.getTimeZone())); + //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + Calendar.getInstance().getTime()); + //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + s.format(Calendar.getInstance().getTime())); + return s.format(Calendar.getInstance().getTime()); + } + + private PdfBean preparePdfBean(HttpServletRequest request,ReportRuntime rr) { + PdfBean pb = new PdfBean(); + + pb.setUserId(AppUtils.getUserID(request)); + + pb.setWhereToShowPageNumber(Globals.getPageNumberPosition()); + pb.setAlternateColor(Globals.isDataAlternateColor()); + pb.setTimestampPattern(Globals.getDatePattern()); + + int temp = -1; + try { + temp = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE)); + } catch (NumberFormatException e) {} + pb.setCurrentPage(temp); + + //pb.setPortrait( trueORfalse(request.getParameter("isPortrait"),true)); + pb.setPortrait(trueORfalse(rr.getPDFOrientation() == "portait"?"true":"false", true)); + //pb.setCoverPageIncluded( trueORfalse(request.getParameter("isCoverPageIncluded"), true)); + //if(Globals.isCoverPageNeeded()) { + pb.setCoverPageIncluded(Globals.isCoverPageNeeded()?rr.isPDFCoverPage():false); + //} + pb.setTitle(nvl(request.getParameter("title"))); + pb.setPagesize(nvls(request.getParameter("pagesize"),"LETTER")); + + pb.setLogo1Url(rr.getPDFLogo1()); + pb.setLogo2Url(rr.getPDFLogo2()); + pb.setLogo1Size(rr.getPDFLogo1Size()); + pb.setLogo2Size(rr.getPDFLogo2Size()); + pb.setFullWebContextPath(request.getSession().getServletContext().getRealPath(File.separator)); + + + pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart()); + + String id = nvl(request.getParameter("pdfAttachmentKey")).trim(); + String log_id = nvl(request.getParameter("log_id")).trim(); + if(id.length()>0 && log_id.length()>0) + pb.setAttachmentOfEmail(true); + + return pb; + } + + private boolean trueORfalse(String str) { + return (str != null) && (str.equalsIgnoreCase("true")); + } + + private boolean trueORfalse(String str,boolean b_default) { + return str==null ? b_default : (str.equalsIgnoreCase("true")); + } + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/BarChartOptions.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/BarChartOptions.java new file mode 100644 index 00000000..7e99dc6e --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/BarChartOptions.java @@ -0,0 +1,75 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +public class BarChartOptions { + private boolean verticalOrientation; + private boolean stackedChart; + private boolean displayBarControls; + private boolean xAxisDateType; + private boolean minimizeXAxisTickers; + private boolean timeAxis; + private boolean yAxisLogScale; + + public boolean isVerticalOrientation() { + return verticalOrientation; + } + public void setVerticalOrientation(boolean verticalOrientation) { + this.verticalOrientation = verticalOrientation; + } + public boolean isStackedChart() { + return stackedChart; + } + public void setStackedChart(boolean stackedChart) { + this.stackedChart = stackedChart; + } + public boolean isDisplayBarControls() { + return displayBarControls; + } + public void setDisplayBarControls(boolean displayBarControls) { + this.displayBarControls = displayBarControls; + } + public boolean isxAxisDateType() { + return xAxisDateType; + } + public void setxAxisDateType(boolean xAxisDateType) { + this.xAxisDateType = xAxisDateType; + } + public boolean isMinimizeXAxisTickers() { + return minimizeXAxisTickers; + } + public void setMinimizeXAxisTickers(boolean minimizeXAxisTickers) { + this.minimizeXAxisTickers = minimizeXAxisTickers; + } + public boolean isTimeAxis() { + return timeAxis; + } + public void setTimeAxis(boolean timeAxis) { + this.timeAxis = timeAxis; + } + public boolean isyAxisLogScale() { + return yAxisLogScale; + } + public void setyAxisLogScale(boolean yAxisLogScale) { + this.yAxisLogScale = yAxisLogScale; + } + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CategoryAxisJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CategoryAxisJSON.java new file mode 100644 index 00000000..93fab6e9 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CategoryAxisJSON.java @@ -0,0 +1,24 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +public class CategoryAxisJSON extends IndexValueJSON { + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartD3Helper.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartD3Helper.java new file mode 100644 index 00000000..18d31278 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartD3Helper.java @@ -0,0 +1,4073 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.commons.lang.time.DateUtils; +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.ReportHandler; +import org.openecomp.portalsdk.analytics.model.base.ChartSeqComparator; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.HtmlStripper; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.view.ReportData; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.web.support.UserUtils; + +public class ChartD3Helper { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChartD3Helper.class); + + + private ReportRuntime reportRuntime; + private String chartType; + + public static final long HOUR = 3600*1000; + public static final long DAY = 3600*1000*24; + public static final long MONTH = 3600*1000*24*31; + public static final long YEAR = 3600*1000*24*365; + + + public ChartD3Helper() { + + } + + /** + * @return the chartType + */ + public String getChartType() { + return chartType; + } + + /** + * @param chartType the chartType to set + */ + public void setChartType(String chartType) { + this.chartType = chartType; + } + + public ChartD3Helper(ReportRuntime rr) { + this.reportRuntime = rr; + } + + public String createVisualization(String reportID, HttpServletRequest request) throws RaptorException { + //From annotations chart + clearReportRuntimeBackup(request); + + //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); + final Long user_id = new Long((long) UserUtils.getUserId(request)); + //String action = request.getParameter(AppConstants.RI_ACTION); + //String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + + ReportHandler rh = new ReportHandler(); + ReportData reportData = null; + HashMap chartOptionsMap = new HashMap(); + try { + if(reportID !=null) { + reportRuntime = rh.loadReportRuntime(request, reportID, true, 1); + setChartType(reportRuntime.getChartType()); + reportData = reportRuntime.loadReportData(0, user_id.toString(), 10000,request, false); + } + + + + String rotateLabelsStr = ""; + rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle()); + if(rotateLabelsStr.toLowerCase().equals("standard")) { + rotateLabelsStr = "0"; + } else if (rotateLabelsStr.toLowerCase().equals("up45")) { + rotateLabelsStr = "45"; + } else if (rotateLabelsStr.toLowerCase().equals("down45")) { + rotateLabelsStr = "-45"; + } else if (rotateLabelsStr.toLowerCase().equals("up90")) { + rotateLabelsStr = "90"; + } else if (rotateLabelsStr.toLowerCase().equals("down90")) { + rotateLabelsStr = "-90"; + } else + rotateLabelsStr = "0"; + + String width = (AppUtils.getRequestNvlValue(request, "width").length()>0?AppUtils.getRequestNvlValue(request, "width"):(AppUtils.nvl(reportRuntime.getChartWidth()).length()>0?reportRuntime.getChartWidth():"700")); + String height = (AppUtils.getRequestNvlValue(request, "height").length()>0?AppUtils.getRequestNvlValue(request, "height"):(AppUtils.nvl(reportRuntime.getChartHeight()).length()>0?reportRuntime.getChartHeight():"300")); + String animationStr = (AppUtils.getRequestNvlValue(request, "animation").length()>0?AppUtils.getRequestNvlValue(request, "animation"):new Boolean(reportRuntime.isAnimateAnimatedChart()).toString()); + + String rotateLabels = (AppUtils.getRequestNvlValue(request, "rotateLabels").length()>0?AppUtils.getRequestNvlValue(request, "rotateLabels"):(rotateLabelsStr.length()>0?rotateLabelsStr:"0")); + String staggerLabelsStr = (AppUtils.getRequestNvlValue(request, "staggerLabels").length()>0?AppUtils.getRequestNvlValue(request, "staggerLabels"):"false"); + String showMaxMinStr = (AppUtils.getRequestNvlValue(request, "showMaxMin").length()>0?AppUtils.getRequestNvlValue(request, "showMaxMin"):"false"); + String showControlsStr = (AppUtils.getRequestNvlValue(request, "showControls").length()>0?AppUtils.getRequestNvlValue(request, "showControls"):new Boolean(reportRuntime.displayBarControls()).toString()); + String showLegendStr = (AppUtils.getRequestNvlValue(request, "showLegend").length()>0?AppUtils.getRequestNvlValue(request, "showLegend"):new Boolean(!new Boolean(reportRuntime.hideChartLegend())).toString()); + String topMarginStr = AppUtils.getRequestNvlValue(request, "topMargin"); + String topMargin = (AppUtils.nvl(topMarginStr).length()<=0)?(reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30"):topMarginStr; + String bottomMarginStr = AppUtils.getRequestNvlValue(request, "bottomMargin"); + String bottomMargin = (AppUtils.nvl(bottomMarginStr).length()<=0)?(reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50"):bottomMarginStr; + String leftMarginStr = AppUtils.getRequestNvlValue(request, "leftMargin"); + String leftMargin = (AppUtils.nvl(leftMarginStr).length()<=0)?(reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100"):leftMarginStr; + String rightMarginStr = AppUtils.getRequestNvlValue(request, "rightMargin"); + String rightMargin = (AppUtils.nvl(rightMarginStr).length()<=0)?(reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160"):rightMarginStr; + String showTitleStr = (AppUtils.getRequestNvlValue(request, "showTitle").length()>0?AppUtils.getRequestNvlValue(request, "showTitle"):new Boolean(reportRuntime.displayChartTitle()).toString()); + String subType = AppUtils.getRequestNvlValue(request, "subType").length()>0?AppUtils.getRequestNvlValue(request, "subType"):(AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():""); + String stackedStr = AppUtils.getRequestNvlValue(request, "stacked").length()>0?AppUtils.getRequestNvlValue(request, "stacked"):new Boolean(reportRuntime.isChartStacked()).toString(); + String horizontalBar = AppUtils.getRequestNvlValue(request, "horizontalBar").length()>0?AppUtils.getRequestNvlValue(request, "horizontalBar"):new Boolean(reportRuntime.isHorizontalOrientation()).toString(); + String barRealTimeAxis = AppUtils.getRequestNvlValue(request, "barRealTimeAxis"); + String barReduceXAxisLabels = AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels").length()>0?AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels"):new Boolean(reportRuntime.isLessXaxisTickers()).toString();; + String timeAxis = AppUtils.getRequestNvlValue(request, "timeAxis").length()>0?AppUtils.getRequestNvlValue(request, "timeAxis"):new Boolean(reportRuntime.isTimeAxis()).toString(); + String logScale = AppUtils.getRequestNvlValue(request, "logScale").length()>0?AppUtils.getRequestNvlValue(request, "logScale"):new Boolean(reportRuntime.isLogScale()).toString(); + String precision = AppUtils.getRequestNvlValue(request, "precision").length()>0?AppUtils.getRequestNvlValue(request, "precision"):"2"; + + + chartOptionsMap.put("width", width); + chartOptionsMap.put("height", height); + chartOptionsMap.put("animation", animationStr); + chartOptionsMap.put("rotateLabels", rotateLabels); + chartOptionsMap.put("staggerLabels", staggerLabelsStr); + chartOptionsMap.put("showMaxMin", showMaxMinStr); + chartOptionsMap.put("showControls", showControlsStr); + chartOptionsMap.put("showLegend", showLegendStr); + chartOptionsMap.put("topMargin", topMargin); + chartOptionsMap.put("bottomMargin", bottomMargin); + chartOptionsMap.put("leftMargin", leftMargin); + chartOptionsMap.put("rightMargin", rightMargin); + chartOptionsMap.put("showTitle", showTitleStr); + chartOptionsMap.put("subType", subType); + chartOptionsMap.put("stacked", stackedStr); + chartOptionsMap.put("horizontalBar", horizontalBar); + chartOptionsMap.put("timeAxis", timeAxis); + chartOptionsMap.put("barRealTimeAxis", barRealTimeAxis); + chartOptionsMap.put("barReduceXAxisLabels", barReduceXAxisLabels); + + chartOptionsMap.put("logScale", logScale); + chartOptionsMap.put("precision", precision); + + + } catch (RaptorException ex) { + ex.printStackTrace(); + } + return createVisualization(reportRuntime, chartOptionsMap, request); + } + + public String createVisualization(ReportRuntime reportRuntime, HttpServletRequest request) throws RaptorException { + + String rotateLabelsStr = ""; + rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle()); + if(rotateLabelsStr.toLowerCase().equals("standard")) { + rotateLabelsStr = "0"; + } else if (rotateLabelsStr.toLowerCase().equals("up45")) { + rotateLabelsStr = "45"; + } else if (rotateLabelsStr.toLowerCase().equals("down45")) { + rotateLabelsStr = "-45"; + } else if (rotateLabelsStr.toLowerCase().equals("up90")) { + rotateLabelsStr = "90"; + } else if (rotateLabelsStr.toLowerCase().equals("down90")) { + rotateLabelsStr = "-90"; + } else + rotateLabelsStr = "0"; + + HashMap chartOptionsMap = new HashMap(); + chartOptionsMap.put("width", reportRuntime.getChartWidth()); + chartOptionsMap.put("height", reportRuntime.getChartHeight()); + chartOptionsMap.put("animation", new Boolean(reportRuntime.isAnimateAnimatedChart()).toString()); + chartOptionsMap.put("rotateLabels", rotateLabelsStr); + chartOptionsMap.put("staggerLabels", "false"); + chartOptionsMap.put("showMaxMin", "false"); + chartOptionsMap.put("showControls", new Boolean(reportRuntime.displayBarControls()).toString()); + chartOptionsMap.put("showLegend", new Boolean(!reportRuntime.hideChartLegend()).toString()); + chartOptionsMap.put("topMargin", reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30"); + chartOptionsMap.put("bottomMargin", reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50"); + chartOptionsMap.put("leftMargin", reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100"); + chartOptionsMap.put("rightMargin", reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160"); + chartOptionsMap.put("showTitle", new Boolean(reportRuntime.displayChartTitle()).toString()); + chartOptionsMap.put("subType", (AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():"")); + chartOptionsMap.put("stacked", new Boolean(reportRuntime.isChartStacked()).toString()); + chartOptionsMap.put("horizontalBar", new Boolean(reportRuntime.isHorizontalOrientation()).toString()); + chartOptionsMap.put("timeAxis", new Boolean(reportRuntime.isTimeAxis()).toString()); + chartOptionsMap.put("barReduceXAxisLabels", new Boolean(reportRuntime.isLessXaxisTickers()).toString()); + + chartOptionsMap.put("logScale", new Boolean(reportRuntime.isLogScale()).toString()); + chartOptionsMap.put("precision", "2"); + + + + return createVisualization(reportRuntime, chartOptionsMap, request); + } + + public String createVisualization(ReportRuntime reportRuntime, HashMap chartOptionsMap, HttpServletRequest request) throws RaptorException { + + //String width, String height, boolean animation, String rotateLabels, boolean staggerLabels, boolean showMaxMin, boolean showLegend, boolean showControls, String topMargin, String bottomMargin, boolean showTitle, String subType + + boolean isEmbedded = false; + if(request.getParameter("embedded")!=null) { + isEmbedded = true; + } + String width = chartOptionsMap.get("width"); + String height = chartOptionsMap.get("height"); + boolean animation = getBooleanValue(chartOptionsMap.get("animation"), true); + String rotateLabels = chartOptionsMap.get("rotateLabels"); + boolean staggerLabels = getBooleanValue(chartOptionsMap.get("staggerLabels")); + boolean showMaxMin = getBooleanValue(chartOptionsMap.get("showMaxMin"), false); + boolean showLegend = getBooleanValue(chartOptionsMap.get("showLegend"), true); + boolean showControls = getBooleanValue(chartOptionsMap.get("showControls"), true); + String topMargin = chartOptionsMap.get("topMargin"); + String bottomMargin = chartOptionsMap.get("bottomMargin"); + String leftMargin = chartOptionsMap.get("leftMargin"); + String rightMargin = chartOptionsMap.get("rightMargin"); + boolean showTitle = getBooleanValue(chartOptionsMap.get("showTitle"), true); + String subType = chartOptionsMap.get("subType"); + boolean stacked = getBooleanValue(chartOptionsMap.get("stacked"), false); + boolean horizontalBar = getBooleanValue(chartOptionsMap.get("horizontalBar"), false); + boolean barRealTimeAxis = getBooleanValue(chartOptionsMap.get("barRealTimeAxis"), true); + boolean barReduceXAxisLabels= getBooleanValue(chartOptionsMap.get("barReduceXAxisLabels"), false); + boolean timeAxis = getBooleanValue(chartOptionsMap.get("timeAxis"), true); + + + boolean logScale = getBooleanValue(chartOptionsMap.get("logScale"), false); + + int precision = 2; + + try { + precision = Integer.parseInt(chartOptionsMap.get("precision")); + } catch (NumberFormatException ex) { + + } + + final Long user_id = new Long((long) UserUtils.getUserId(request)); + + HttpSession session = null; + session = request.getSession(); + String chartType = reportRuntime.getChartType(); + List l = reportRuntime.getAllColumns(); + List lGroups = reportRuntime.getAllChartGroups(); + HashMap mapYAxis = reportRuntime.getAllChartYAxis(reportRuntime.getReportParamValues()); + //ReportParamValues reportParamValues = reportRuntime.getReportParamValues(); + String chartLeftAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartLeftAxisLabel())); + String chartRightAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartRightAxisLabel())); + + boolean multipleSeries = reportRuntime.isMultiSeries(); + + java.util.HashMap formValues = null; + formValues = getRequestParametersMap(reportRuntime, request); + + + String legendColumnName = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():"Legend Column"; + boolean displayChart = (nvl(chartType).length()>0)&&reportRuntime.getDisplayChart(); + HashMap additionalChartOptionsMap = new HashMap(); + + StringBuffer wholeScript = new StringBuffer(""); + + String title = reportRuntime.getReportTitle(); + + title = parseTitle(title, formValues); + + String chartScriptsPath = (isEmbedded?AppUtils.getChartScriptsPath(""):AppUtils.getChartScriptsPath()); + + if(displayChart) { + DataSet ds = null; + try { + if (!(chartType.equals(AppConstants.GT_HIERARCHICAL) || chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST) || chartType.equals(AppConstants.GT_ANNOTATION_CHART))) { + ds = (DataSet) loadChartData(new Long(user_id).toString(), request); + } else if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) { + String reportSQL = reportRuntime.getWholeSQL(); + String dbInfo = reportRuntime.getDBInfo(); + ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); + if(ds.getRowCount()<=0) { + logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + logger.debug(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY")); + logger.debug(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportSQL)); + logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + } + } else if(chartType.equals(AppConstants.GT_HIERARCHICAL)||chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) { + String reportSQL = reportRuntime.getWholeSQL(); + String dbInfo = reportRuntime.getDBInfo(); + ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); + } + } catch (RaptorException ex) { + //throw new RaptorException("Error while loading chart data", ex); + logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + logger.error(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " ERROR THROWN FOR GIVEN QUERY ")); + logger.error(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportRuntime.getWholeSQL())); + logger.error(EELFLoggerDelegate.debugLogger, ("ERROR STACK TRACE" + ex.getMessage())); + logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + + } + if(ds==null) { + //displayChart = false; + if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) + ds = new DataSet(); + else + displayChart = false; + } + if(displayChart) { + + if (chartType.equals(AppConstants.GT_BAR_3D)) { + + // get category if not give the column name for the data column use this to develop series. + boolean hasCategoryAxis = reportRuntime.hasSeriesColumn(); + + boolean hasCustomizedChartColor = false; + int flag = 0; + flag = hasCategoryAxis?1:0; + Object uniqueElements [] = null; + ArrayList uniqueElementsList = new ArrayList(); + Object uniqueXAxisElements[] = null; + ArrayList ts = new ArrayList(); + //Set ts1 = new HashSet(); + ArrayList ts1 = new ArrayList(); + HashMap columnMap = new HashMap(); + String uniqueXAxisStr = ""; + if(!timeAxis){ + for (int i = 0; i < ds.getRowCount(); i++) { + uniqueXAxisStr = ds.getString(i, 0); + ts1.add(uniqueXAxisStr); + } + } + uniqueElementsList.addAll(ts1); + uniqueXAxisElements = ts1.toArray(); + + if(flag == 1) { + StringBuffer catStr = new StringBuffer(""); + String color=""; + for (int i = 0; i < ds.getRowCount(); i++) { + catStr = new StringBuffer(""); + catStr.append(ds.getString(i, 2)); + try { + if(ds.getString(i, "chart_color")!=null) { + color = ds.getString(i, "chart_color"); + hasCustomizedChartColor = true; + catStr.append("|"+color); + } + } catch (ArrayIndexOutOfBoundsException ex) { + //System.out.println("No Chart Color"); + } + + if(catStr.length()>0) { + //duplicates are avoided + if(!ts.contains(catStr.toString())) + ts.add(catStr.toString()); + + } + /* Get Chart LeftAxis Label even from Range Axis definition. */ + DataColumnType dct = null; + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + if(nvl(chartLeftAxisLabel).length()<=0) { + chartLeftAxisLabel = nvl(dct.getYAxis()); + chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; + } + } + } + + } + //Object uniqueElements [] = ts.toArray(); + //SortedSet s = Collections.synchronizedSortedSet(ts); + uniqueElements = ts.toArray(); + } else { + DataColumnType dct = null; + List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); + //if(columnValuesList.size() == 1) { + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + + if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + if((dct.isChartSeries()!=null && dct.isChartSeries().booleanValue()) || (dct.getChartSeq()!=null && dct.getChartSeq()>0) ) { + + if(nvl(dct.getChartColor()).length()>0) hasCustomizedChartColor = true; + if(hasCustomizedChartColor) { + //duplicates are avoided + if(!ts.contains(dct.getDisplayName()+"|"+nvl(dct.getChartColor()))) + ts.add(dct.getDisplayName()+"|"+nvl(dct.getChartColor())); + } else { + //duplicates are avoided + if(!ts.contains(dct.getDisplayName())) + ts.add(dct.getDisplayName()); + } + if(nvl(chartLeftAxisLabel).length()<=0) { + chartLeftAxisLabel = nvl(dct.getYAxis()); + chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; + } + columnMap.put(dct.getDisplayName(), dct.getColId()); + /* + ts.add(dct.getDisplayName()); + if(nvl(chartLeftAxisLabel).length()<=0) { + chartLeftAxisLabel = nvl(dct.getYAxis()); + chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; + } + columnMap.put(dct.getDisplayName(), dct.getColId()); + */ + } + } + + } + //SortedSet s = Collections.synchronizedSortedSet(ts); + uniqueElements = ts.toArray(); + + } + + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + //wholeScript.append("") + wholeScript.append(" \n" ); + wholeScript.append(" \n"); + if(showTitle) + wholeScript.append("

" + title +"

"); + + wholeScript.append("
\n"); + //js files + wholeScript.append(""); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + //wholeScript.append(" \n"); + //wholeScript.append(" \n"); + wholeScript.append(" \n"); + //json + wholeScript.append(" \n"); + + } else if (chartType.equals(AppConstants.GT_TIME_SERIES)) { + + // get category if not give the column name for the data column use this to develop series. + boolean hasCategoryAxis = reportRuntime.hasSeriesColumn(); + + + final int YEARFLAG = 1; + final int MONTHFLAG = 2; + final int DAYFLAG = 3; + final int HOURFLAG = 4; + final int MINFLAG = 5; + final int SECFLAG = 6; + final int MILLISECFLAG = 7; + final int DAYOFTHEWEEKFLAG = 8; + final int FLAGDATE = 9; + + int flag = 0; + flag = hasCategoryAxis?1:0; + String uniqueElements [] = null; + //TreeSet ts = new TreeSet(); + ArrayList ts = new ArrayList(); + HashMap columnMap = new HashMap(); + //check timeAxis + String dateStr = null; + java.util.Date date = null; + if( ds.getRowCount() > 0) { + dateStr = ds.getString(0, 1); + if(!timeAxis) { + date = getDateFromDateStr(dateStr); + if(date!=null) { + reportRuntime.setTimeAxis(true); + timeAxis = reportRuntime.isTimeAxis(); + + + } + } + } + + ArrayList ts1 = new ArrayList(); + ArrayList uniqueElementsList = new ArrayList(); + Object uniqueXAxisElements[] = null; + String uniqueXAxisStr = ""; + if(!timeAxis){ + for (int i = 0; i < ds.getRowCount(); i++) { + uniqueXAxisStr = ds.getString(i, 0); + ts1.add(uniqueXAxisStr); + } + } + uniqueElementsList.addAll(ts1); + uniqueXAxisElements = ts1.toArray(); + //test start + /* int TOTAL = 0; + int VALUE = 0; + int flagNull = 0; + String KEY = ""; + String COLOR = ""; + TreeSet colorList = new TreeSet(); + for (int i = 0; i < ds.getRowCount(); i++) { + VALUE = 0; + try { + VALUE = Integer.parseInt(ds.getString(i, 2)); + TOTAL = TOTAL+VALUE; + } catch (NumberFormatException ex) { + flagNull = 1; + } + KEY = ds.getString(i, 0); + try { + if(ds.getString(i, "chart_color")!=null) { + colorList.add(KEY+"|"+ds.getString(i, "chart_color")); + } + } catch (ArrayIndexOutOfBoundsException ex) { + System.out.println("No Chart Color"); + } + wholeScript.append("{ \""+ "key" +"\":\""+ KEY+"\", \""+ "y" +"\":"+VALUE+"}, \n"); + + } + StringBuffer color = new StringBuffer(""); + if(colorList.size()>0) { + SortedSet s = Collections.synchronizedSortedSet(colorList); + Object[] colorElements = (Object[]) s.toArray(); + + String element = ""; + + for (int i = 0; i < colorElements.length; i++) { + element = ((String)colorElements[i]); + color.append("'"+element.substring(element.indexOf("|")+1)+"',"); + } + color.deleteCharAt(color.length()-1); + }*/ + + //test end + boolean hasCustomizedChartColor = false; + if(flag == 1) { + StringBuffer catStr = new StringBuffer(""); + String color=""; + for (int i = 0; i < ds.getRowCount(); i++) { + catStr = new StringBuffer(""); + catStr.append(ds.getString(i, 2)); + try { + if(ds.getString(i, "chart_color")!=null) { + color = ds.getString(i, "chart_color"); + hasCustomizedChartColor = true; + catStr.append("|"+color); + } + } catch (ArrayIndexOutOfBoundsException ex) { + //System.out.println("No Chart Color"); + } + + if(catStr.length()>0) { + //duplicates are avoided + if(!ts.contains(catStr.toString())) + ts.add(catStr.toString()); + + } + } + //Object uniqueElements [] = ts.toArray(); + //SortedSet s = Collections.synchronizedSortedSet(ts); + //uniqueElements = (String[]) ts.toArray(); + DataColumnType dct = null; + List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); + if(yTextSeries.size()==1) { + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + //System.out.println(dct.getDisplayName() + " " + yText); + if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + if(nvl(chartLeftAxisLabel).length()<=0) { + chartLeftAxisLabel = nvl(dct.getYAxis()); + chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; + } + } + } + } + Object tempArray[] = ts.toArray(); + uniqueElements = Arrays.copyOf(tempArray, tempArray.length, String[].class); + + } else { + DataColumnType dct = null; + + List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); + //if(columnValuesList.size() == 1) { + int dctIndex = 0; + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + //System.out.println(dct.getDisplayName() + " " + yText); + if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + if(yTextSeries.contains((String)dct.getDisplayName())) { + if(nvl(dct.getChartColor()).length()>0) hasCustomizedChartColor = true; + if(hasCustomizedChartColor) { + //duplicates are avoided + if(!ts.contains(dct.getDisplayName()+"|"+nvl(dct.getChartColor()))) + ts.add(dct.getDisplayName()+"|"+nvl(dct.getChartColor())); + } else { + //duplicates are avoided + if(!ts.contains(dct.getDisplayName())) + ts.add(dct.getDisplayName()); + } + if(nvl(chartLeftAxisLabel).length()<=0) { + chartLeftAxisLabel = nvl(dct.getYAxis()); + chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; + } + if(nvl(chartRightAxisLabel).length()>0) { + String dctYAxis = nvl(dct.getYAxis()); + String yAxis = (dctYAxis.indexOf("|")!=-1)?dctYAxis.substring(0,dctYAxis.indexOf("|")):dctYAxis; + if(chartRightAxisLabel.equals(yAxis)) { + if(ts.contains(dct.getDisplayName())) { + if(hasCustomizedChartColor) { + ts.set(dctIndex, dct.getDisplayName()+"|R|"+nvl(dct.getChartColor())); + } else { + ts.set(dctIndex, dct.getDisplayName()+"|R"); + } + } + } + } + columnMap.put(dct.getDisplayName(), dct.getColId()); + } + dctIndex++; + } + + } + + //SortedSet s = Collections.synchronizedSortedSet(ts); + Object tempArray[] = ts.toArray(); + uniqueElements = Arrays.copyOf(tempArray, tempArray.length, String[].class); + //uniqueElements = (String[]) ts.toArray(); + + } + + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append(" \n" ); + + wholeScript.append(" \n"); + + if(showTitle) + wholeScript.append("

" + title +"

"); + + + wholeScript.append("
\n"); + //js files + wholeScript.append("\n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + //wholeScript.append(" \n"); + //if(multipleSeries) + //wholeScript.append(" \n"); + + //json + wholeScript.append(" \n"); + + } else if (chartType.equals(AppConstants.GT_PIE) || chartType.equals(AppConstants.GT_PIE_3D)) { + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append(" \n" ); + wholeScript.append(" \n"); + + if(showTitle) + wholeScript.append("

" + title +"

"); + + wholeScript.append("
"); + //"\n"); + //js files + wholeScript.append("\n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + + } else if (chartType.equals(AppConstants.GT_ANNOTATION_CHART) || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) { + + boolean timeCharts = chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS); + + String dateStr = null; + java.util.Date date = null; + + final int YEARFLAG = 1; + final int MONTHFLAG = 2; + final int DAYFLAG = 3; + final int HOURFLAG = 4; + final int MINFLAG = 5; + final int SECFLAG = 6; + final int MILLISECFLAG = 7; + final int DAYOFTHEWEEKFLAG = 8; + final int FLAGDATE = 9; + + int flagNoDate = 0; + + int MAXNUM = 0; + int YAXISNUM = 0; + int flagNull = 0; + + double YAXISDOUBLENUM = 0.0; + double MAXDOUBLENUM = 0.0; + int MAXNUMDECIMALPLACES = 0; + + int formatFlag = 0; + + TreeSet dateStrList = new TreeSet(); + // added to store all date elements + SortedSet sortSet = new TreeSet(); + int count = 0; + + int flag = 0; + boolean hasCategoryAxis = reportRuntime.hasSeriesColumn(); + flag = hasCategoryAxis?1:0; + + + String anomalyText = ""; + + StringBuffer dataStrBuf = new StringBuffer(""); + StringBuffer annotationsStrBuf = new StringBuffer(""); + + String xAxisLabel = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():""; + + //finding actual string + String actualText = ""; + DataColumnType dct = null; + for (Iterator iter = l.iterator(); iter.hasNext();) { + dct = (DataColumnType) iter.next(); + if((dct.getChartSeq()!=null && dct.getChartSeq() >=0) && !AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) { + //if(AppUtils.nvl(dct.getDisplayName()).toLowerCase().contains("actual")) { + actualText = dct.getDisplayName(); + break; + //} + } + } + + int anomalyRec = 0; + int columnIndex = 1; + ArrayList columnNames = new ArrayList(); + ArrayList columnValues = new ArrayList(); + Set set = null; + String columnName = ""; + String columnValue = ""; + long minDate = 0L; + long maxDate = 0L; + StringBuffer seriesBuffer = new StringBuffer(""); + + for (int i = 0; i < ds.getRowCount(); i++) { + columnNames = new ArrayList(); + columnValues = new ArrayList(); + columnName = ""; + columnValue = ""; + columnIndex = 1; + anomalyText = ""; + dateStr = ds.getString(i, 0); + date = getDateFromDateStr(dateStr); + if(date.getTime() > maxDate ) + maxDate = date.getTime(); + + formatFlag = getFlagFromDateStr(dateStr); + + + for (;columnIndex=0) && !AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) { + if((!timeCharts && !AppUtils.nvl(dct.getColId()).toLowerCase().equals("anomaly_text")) && AppUtils.nvl(dct.getColId()).toLowerCase().equals(columnName.toLowerCase())) { + dataStrBuf.append(","+columnValue); + break; + } else if(timeCharts && AppUtils.nvl(dct.getColId()).toLowerCase().equals(columnName.toLowerCase())){ + dataStrBuf.append(","+columnValue); + //break; + } + } + } + } + + dataStrBuf.append("],\n"); + if(!timeCharts) { + if(AppUtils.nvl(anomalyText).length()>0) { + ++anomalyRec; + annotationsStrBuf.append("anns.push( {\n"); + annotationsStrBuf.append(" series: '"+actualText+"',\n"); + annotationsStrBuf.append(" x: moment(\""+dateStr+"\"),\n"); + annotationsStrBuf.append(" shortText: '"+ IntToLetter(anomalyRec).toUpperCase() +"',\n"); + annotationsStrBuf.append(" text: '"+ anomalyText + "'\n"); + annotationsStrBuf.append("});\n"); + //anomalyRec++; + } + + } + } + + //if(!timeCharts) + //anomalyRec = anomalyRec - 1; + + minDate = maxDate - (new Long(reportRuntime.getZoomIn()).longValue()*60*60*1000); + System.out.println(new java.util.Date(maxDate) + " " + new java.util.Date(minDate) + " " + reportRuntime.getZoomIn()); + if(dataStrBuf.lastIndexOf(",")!= -1) + dataStrBuf.deleteCharAt(dataStrBuf.lastIndexOf(",")); + + wholeScript = new StringBuffer(""); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append(" \n"); + //wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append("\n"); + + wholeScript.append("\n "); + wholeScript.append("\n"); + wholeScript.append("\n"); + wholeScript.append(" \n"); + +/* if(showTitle) + wholeScript.append("

" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "

\n"); +*/ + wholeScript.append(" \n"); + if(showTitle) { + wholeScript.append(" \n "); + wholeScript.append(" \n "); + } + + wholeScript.append(" \n "); + + wholeScript.append(" \n "); + wholeScript.append(" \n "); + + wholeScript.append(" \n "); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) { + wholeScript.append(" \n"); + } + wholeScript.append(" \n"); + if(anomalyRec > 0) { + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + } + wholeScript.append("
\n "); + wholeScript.append("
"+title+"
\n"); + wholeScript.append("
\n "); + if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()<=0 || reportRuntime.getLegendPosition().equals("top")) { + wholeScript.append("
\n"); + } + wholeScript.append("
\n"); + wholeScript.append("
\n"); + + int heightInt = 0; + if(nvl(height).length() > 0) { + try { + heightInt = new Integer(height).intValue(); + heightInt -= 50; + } catch(Exception ex) { + if(height.endsWith("px")) { + try { + heightInt = new Integer(height.substring(0, height.indexOf("px"))); + heightInt -= 50; + } catch (Exception ex1) { + heightInt = 420; + } + } else { + heightInt = 420; + } + } + } else heightInt = 420; + if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) { + wholeScript.append("
\n"); + wholeScript.append("
\n"); + wholeScript.append("
\n"); + wholeScript.append("
\n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n" ); + wholeScript.append(" \n"); + wholeScript.append("
Anomaly Description
\n"); + wholeScript.append("
\n"); + + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(""); + + + } else if (chartType.equals(AppConstants.GT_SCATTER)) { + + wholeScript.append("\n"); + wholeScript.append(" \n" ); + wholeScript.append(" \n"); + wholeScript.append("
"); + //js files + wholeScript.append("\n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append(" \n"); + wholeScript.append("\n"); + } else if (chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) { + + StringBuffer dataStr = new StringBuffer(""); + StringBuffer groupBuffer = new StringBuffer(""); + StringBuffer s = new StringBuffer(""); + dataStr.append("{"); + dataStr.append(" \"ss4262\":{\n"); + String mid = ""; + String mid_old = ""; + String level = "-1"; + String level_old = "-1"; + String eid = ""; + for (int i = 0; i < ds.getRowCount(); i++) { + mid = ds.getString(i, "mid"); + level = ds.getString(i, "level1"); + eid = ds.getString(i, "eid"); + if(mid.equals(mid_old)) { + dataStr.append("\""+ eid +"\": 9956,\n"); + } else { + if(dataStr.lastIndexOf(",")!= -1) + dataStr.deleteCharAt(dataStr.lastIndexOf(",")); + //if(Integer.parseInt(level_old)==Integer.parseInt(level)) + //dataStr.append("},\n"); + if (Integer.parseInt(level_old)0) { + /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL"));*/ + reportSQL = Utils.replaceInString(reportSQL, fieldDisplay, nvl( + paramValue, "NULL")); + } + /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL"));*/ + reportSQL = Utils.replaceInString(reportSQL, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + reportSQL = Utils.replaceInString(reportSQL, fieldDisplay , nvl( + paramValue, "NULL")); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL)); + String legendCol = "1 a"; + // String valueCol = "1"; + StringBuffer groupCol = new StringBuffer(); + StringBuffer seriesCol = new StringBuffer(); + StringBuffer valueCols = new StringBuffer(); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, request); + if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + legendCol = getSelectExpr(dc, colName)+" " + dc.getColId(); + // if(dc.getChartSeq()>0) + // valueCol = "NVL("+colName+", 0) "+dc.getColId(); + if ((!nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + && (dc.getChartSeq()!=null && dc.getChartSeq().intValue() <= 0) && dc.isGroupBreak()) { + groupCol.append(", "); + groupCol.append(colName + " " + dc.getColId()); + } + } // for + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(dc.isChartSeries()!=null && dc.isChartSeries().booleanValue()) { + //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); + seriesCol.append(", "+ getSelectExpr(dc,getColumnSelectStr(dc, request))+ " " + dc.getColId()); + } + } + + /*for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(!dc.isChartSeries() && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); + seriesCol.append(", "+ formatChartColumn(getSelectExpr(dc,getColumnSelectStr(dc, paramValues)))+ " " + dc.getColId()); + } + }*/ + + for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, request); + String paramValue = ""; + if(AppUtils.nvl(colName).startsWith("[")) { + if (reportRuntime.getFormFieldList() != null) { + for (Iterator iterC = reportRuntime.getFormFieldList().getFormField().iterator(); iterC.hasNext();) { + FormFieldType fft = (FormFieldType) iterC.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); + String formfield_value = ""; + if(AppUtils.nvl(fieldDisplay).equals(colName)) { + formfield_value = AppUtils.getRequestNvlValue(request, fieldId); + paramValue = nvl(formfield_value); + } + } + + } + + seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:"null") + " " + dc.getColId()); + } else { + //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); + seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:formatChartColumn(colName)) + " " + dc.getColId()); + } + } // for + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = dc.getDisplayName(); + String colValue = getColumnSelectStr(dc, request); + //String colName = getColumnSelectStr(dc, formGrid); + if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) + seriesCol.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); + if (colName.equals(AppConstants.RI_CHART_COLOR)) + seriesCol.append(", " + colValue + " " + AppConstants.RI_CHART_COLOR ); + if(colName.equals(AppConstants.RI_CHART_MARKER_START)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_START + " " + AppConstants.RI_CHART_MARKER_START ); + if(colName.equals(AppConstants.RI_CHART_MARKER_END)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_END + " " + AppConstants.RI_CHART_MARKER_END ); + if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_LEFT)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_LEFT + " " + AppConstants.RI_CHART_MARKER_TEXT_LEFT ); + if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_RIGHT)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT + " " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT ); + //if(colName.equals(AppConstants.RI_ANOMALY_TEXT)) + //seriesCol.append(", " + AppConstants.RI_ANOMALY_TEXT + " " + AppConstants.RI_ANOMALY_TEXT ); + } + + //debugLogger.debug("ReportSQL Chart " + reportSQL ); + /*for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); + valueCols.append("," + formatChartColumn(colName) + " " + dc.getColId()); + } // for + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //if(colName.equals(AppConstants.RI_CHART_TOTAL_COL) || colName.equals(AppConstants.RI_CHART_COLOR)) { + if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) + valueCols.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); + if (colName.equals(AppConstants.RI_CHART_COLOR)) + valueCols.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR ); + if (colName.equals(AppConstants.RI_CHART_INCLUDE)) + valueCols.append(", " + AppConstants.RI_CHART_INCLUDE + " " + AppConstants.RI_CHART_INCLUDE ); + //} + }*/ + String final_sql = ""; + reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM "); + reportSQL = Utils.replaceInString(reportSQL, " From ", " FROM "); + reportSQL = Utils.replaceInString(reportSQL, " select ", " SELECT "); + reportSQL = Utils.replaceInString(reportSQL, " union ", " UNION "); + //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); +// if(reportSQL.indexOf("UNION") != -1) { +// if(reportSQL.indexOf("FROM(")!=-1) +// final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM(") ); +// else if (reportSQL.indexOf("FROM (")!=-1) +// final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM (") ); +// //TODO ELSE THROW ERROR +// } +// else { +// final_sql += " "+reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM ")); +// } + int pos = 0; + int pos_first_select = 0; + int pos_dup_select = 0; + int pos_prev_select = 0; + int pos_last_select = 0; + if (reportSQL.indexOf("FROM", pos)!=-1) { + pos = reportSQL.indexOf("FROM", pos); + pos_dup_select = reportSQL.lastIndexOf("SELECT",pos); + pos_first_select = reportSQL.indexOf("SELECT");//,pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select)); + if(pos_dup_select > pos_first_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select)); + //pos_dup_select1 = pos_dup_select; + pos_prev_select = pos_first_select; + pos_last_select = pos_dup_select; + while (pos_last_select > pos_prev_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select)); + pos = reportSQL.indexOf("FROM", pos+2); + pos_prev_select = pos_last_select; + pos_last_select = reportSQL.lastIndexOf("SELECT",pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select)); + } + } + + } + final_sql += " "+reportSQL.substring(pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("Final SQL " + final_sql)); + String sql = "SELECT " + legendCol + ", " + legendCol+"_1" + seriesCol.toString()+ nvl(valueCols.toString(), ", 1") + + groupCol.toString() + + final_sql; + logger.debug(EELFLoggerDelegate.debugLogger, ("Final sql in generateChartSQL " +sql)); + + return sql; + } // generateChartSQL + + private String getColumnSelectStr(DataColumnType dc, HttpServletRequest request) { + //String colName = dc.isCalculated() ? dc.getColName() + // : ((nvl(dc.getTableId()).length() > 0) ? (dc.getTableId() + "." + dc + // .getColName()) : dc.getColName()); + String colName = dc.getColName(); + String paramValue = null; + //if (dc.isCalculated()) { + if (reportRuntime.getFormFieldList() != null) { + for (Iterator iter = reportRuntime.getFormFieldList().getFormField().iterator(); iter.hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); + String formfield_value = ""; + formfield_value = AppUtils.getRequestNvlValue(request, fieldId); + paramValue = nvl(formfield_value); + if(paramValue.length()>0) { + /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL"));*/ + colName = Utils.replaceInString(colName, "'" + fieldDisplay + "'", "'"+nvl( + paramValue, "NULL")+"'"); + colName = Utils.replaceInString(colName, fieldDisplay, nvl( + paramValue, "NULL")); + } + } + return colName; + } + //} + return colName; + } // getColumnSelectStr + + + + public String getSelectExpr(DataColumnType dct) { + // String colName = + // dct.isCalculated()?dct.getColName():((nvl(dct.getTableId()).length()>0)?(dct.getTableId()+"."+dct.getColName()):dct.getColName()); + return getSelectExpr(dct, dct.getColName() /* colName */); + } // getSelectExpr + + private String getSelectExpr(DataColumnType dct, String colName) { + String colType = dct.getColType(); + if (colType.equals(AppConstants.CT_CHAR) + || ((nvl(dct.getColFormat()).length() == 0) && (!colType + .equals(AppConstants.CT_DATE)))) + return colName; + else + return "DATE_FORMAT(" + colName + ", '" + + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')"; + } // getSelectExpr + + private String formatChartColumn(String colName) { + logger.debug(EELFLoggerDelegate.debugLogger, ("Format Chart Column Input colName " + colName)); + colName = colName.trim(); + colName = Utils.replaceInString(colName, "TO_CHAR", "to_char"); + colName = Utils.replaceInString(colName, "to_number", "TO_NUMBER"); + //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); + colName = colName.replaceAll(",[\\s]*\\(", ",("); + StringBuffer colNameBuf = new StringBuffer(colName); + int pos = 0, posFormatStart = 0, posFormatEnd = 0; + String format = ""; + + if(colNameBuf.indexOf("999")==-1 && colNameBuf.indexOf("990")==-1) { + logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); + return colNameBuf.toString(); + } + + while (colNameBuf.indexOf("to_char")!=-1) { + if(colNameBuf.indexOf("999")!=-1 || colNameBuf.indexOf("990")!=-1) { + pos = colNameBuf.indexOf("to_char"); + colNameBuf.insert(pos, " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ("); + pos = colNameBuf.indexOf("to_char"); + colNameBuf.replace(pos, pos+7, "TO_CHAR"); + //colName = Utils.replaceInString(colNameBuf.toString(), "to_char", " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ( TO_CHAR "); + logger.debug(EELFLoggerDelegate.debugLogger, ("After adding to_number " + colNameBuf.toString())); + //posFormatStart = colNameBuf.lastIndexOf(",'")+1; + posFormatStart = colNameBuf.indexOf(",'", pos)+1; + posFormatEnd = colNameBuf.indexOf(")",posFormatStart); + logger.debug(EELFLoggerDelegate.debugLogger, (posFormatStart + " " + posFormatEnd + " "+ pos)); + format = colNameBuf.substring(posFormatStart, posFormatEnd); + //posFormatEnd = colNameBuf.indexOf(")",posFormatEnd); + colNameBuf.insert(posFormatEnd+1, " ," + format + ") , "+ format + ")"); + logger.debug(EELFLoggerDelegate.debugLogger, ("colNameBuf " + colNameBuf.toString())); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); + return colNameBuf.toString(); + } + + public List getChartValueColumnsList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = reportRuntime.getAllColumns(); + + ArrayList chartValueCols = new ArrayList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = reportRuntime.getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } + else if(filter == 0) chartValueCols.add(dc); + } else chartValueCols.add(dc); + } +// } else +// chartValueCols.add(dc); + } // for + Collections.sort(chartValueCols, new ChartSeqComparator()); + return chartValueCols; + } // getChartValueColumnsList + + public String parseTitle(String title, HashMap formValues) { + Set set = formValues.entrySet(); + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + if(title.indexOf("["+ entry.getKey() + "]")!= -1) { + title = Utils.replaceInString(title, "["+entry.getKey()+"]", nvl( + (String) entry.getValue(), "")); + } + } + return title; + } + + public java.util.Date getDateFromDateStr(String dateStr) { + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + SimpleDateFormat EEEMMDDYYYYFormat = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00 + SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); + SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat timestampHrFormat = new SimpleDateFormat("yyyy-MM-dd HH"); + SimpleDateFormat timestampDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + SimpleDateFormat MMDDYYYYHHFormat = new SimpleDateFormat("MM/dd/yyyy HH"); + SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); + SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); + SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); + SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + SimpleDateFormat timestampFormat1 = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S"); + SimpleDateFormat timestamp_W_dash = new SimpleDateFormat("yyyyMMddHHmmss"); + SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat YYYYFormat = new SimpleDateFormat("yyyy"); + java.util.Date date = null; + + int formatFlag = 0; + + final int YEARFLAG = 1; + final int MONTHFLAG = 2; + final int DAYFLAG = 3; + final int HOURFLAG = 4; + final int MINFLAG = 5; + final int SECFLAG = 6; + final int MILLISECFLAG = 7; + final int DAYOFTHEWEEKFLAG = 8; + final int FLAGDATE = 9; + /*int yearFlag = 1; + int monthFlag = 2; + int dayFlag = 3; + int hourFlag = 4; + int minFlag = 5; + int secFlag = 6; + int milliSecFlag = 7; + int dayoftheweekFlag = 8; + int flagDate = 10; + */ + + date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + if(date==null) { + date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYOFTHEWEEKFLAG; + } + if(date==null) { + date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + if(date==null) { + //MMDDYYYYHHFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = timestampFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + if(date==null) { + date = timestampHrFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = timestampDayFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = MONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = MMDDYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = timestampFormat1.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = YYYYFormat.parse(dateStr, new ParsePosition(0)); + /* Some random numbers should not satisfy this year format. */ + if(dateStr.length()>4) date = null; + if(date!=null) formatFlag = YEARFLAG; + } + if(date==null) { + date = timestamp_W_dash.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + if(date==null) + date = null; + return date; + } + + public int getFlagFromDateStr(String dateStr) { + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + SimpleDateFormat EEEMMDDYYYYFormat = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00 + SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); + SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat timestampHrFormat = new SimpleDateFormat("yyyy-MM-dd HH"); + SimpleDateFormat timestampDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + SimpleDateFormat MMDDYYYYHHFormat = new SimpleDateFormat("MM/dd/yyyy HH"); + SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); + SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); + SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); + SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + SimpleDateFormat timestampFormat1 = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S"); + SimpleDateFormat timestamp_W_dash = new SimpleDateFormat("yyyyMMddHHmmss"); + SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat YYYYFormat = new SimpleDateFormat("yyyy"); + java.util.Date date = null; + + int formatFlag = 0; + + final int YEARFLAG = 1; + final int MONTHFLAG = 2; + final int DAYFLAG = 3; + final int HOURFLAG = 4; + final int MINFLAG = 5; + final int SECFLAG = 6; + final int MILLISECFLAG = 7; + final int DAYOFTHEWEEKFLAG = 8; + final int FLAGDATE = 9; + /*int yearFlag = 1; + int monthFlag = 2; + int dayFlag = 3; + int hourFlag = 4; + int minFlag = 5; + int secFlag = 6; + int milliSecFlag = 7; + int dayoftheweekFlag = 8; + int flagDate = 10; + */ + + date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + if(date==null) { + date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYOFTHEWEEKFLAG; + } + if(date==null) { + date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + if(date==null) { + //MMDDYYYYHHFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = timestampFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + if(date==null) { + date = timestampHrFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = timestampDayFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = MONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = MMDDYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = timestampFormat1.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = YYYYFormat.parse(dateStr, new ParsePosition(0)); + /* Some random numbers should not satisfy this year format. */ + if(dateStr.length()>4) date = null; + if(date!=null) formatFlag = YEARFLAG; + } + if(date==null) { + date = timestamp_W_dash.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + if(date==null) + date = null; + return formatFlag; + } + + public static String[] reverse(String[] arr) { + List list = Arrays.asList(arr); + Collections.reverse(list); + return (String[])list.toArray(); + } + + public int getNumberOfDecimalPlaces(double num) { + Double d = num; + String[] splitter = d.toString().split("\\."); + splitter[0].length(); // Before Decimal Count + splitter[1].length(); // After Decimal Count + return splitter[1].length(); + } + + public boolean getBooleanValue(String s) { + return getBooleanValue(s,null); + } + + public boolean getBooleanValue(String s, Boolean defaultValue) { + s = nvl(s); + if(s.length()<=0 && defaultValue!=null) return defaultValue.booleanValue(); + else if(s.length()<=0) return false; + else { + if(s.toUpperCase().startsWith("Y") || s.toLowerCase().equals("true")) + return true; + else + return false; + } + } + + + public String IntToLetter(int Int) { + if (Int<27){ + return Character.toString((char)(Int+96)); + } else { + if (Int%26==0) { + return IntToLetter((Int/26)-1)+IntToLetter((Int%26)+1); + } else { + return IntToLetter(Int/26)+IntToLetter(Int%26); + } + } + } + + + + + private void clearReportRuntimeBackup(HttpServletRequest request) { + //Session sess = Sessions.getCurrent(true)getCurrent(); + //HttpSession session = (HttpSession)sess.getNativeSession(); + HttpSession session = request.getSession(); + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + request.removeAttribute(AppConstants.DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.DRILLDOWN_INDEX); + request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + Enumeration enum1 = session.getAttributeNames(); + String attributeName = ""; + while(enum1.hasMoreElements()) { + attributeName = enum1.nextElement(); + if(attributeName.startsWith("parent_")) { + session.removeAttribute(attributeName); + } + } + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID); + session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); + session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP); + session.removeAttribute(AppConstants.SI_MAP); + session.removeAttribute(AppConstants.SI_MAP_OBJECT); + session.removeAttribute(AppConstants.SI_REPORT_DEFINITION); + session.removeAttribute(AppConstants.SI_REPORT_RUNTIME); + session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP); + session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE); + session.removeAttribute(AppConstants.RI_REPORT_DATA); + session.removeAttribute(AppConstants.RI_CHART_DATA); + session.removeAttribute(AppConstants.SI_FORMFIELD_INFO); + session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + + } // clearReportRuntimeBackup + + + public static synchronized java.util.HashMap getRequestParametersMap(ReportRuntime rr, HttpServletRequest request) + { + HashMap valuesMap = new HashMap(); + + ReportFormFields rff = rr.getReportFormFields(); + + int idx = 0; + FormField ff = null; + + Map fieldNameMap = new HashMap(); + int countOfFields = 0 ; + + + for(rff.resetNext(); rff.hasNext(); idx++) { + ff = rff.getNext(); + fieldNameMap.put(ff.getFieldName(), ff.getFieldDisplayName()); + countOfFields++; + } + + List formParameter = new ArrayList(); + String formField = ""; + for(int i = 0 ; i < rff.size(); i++) { + ff = ((FormField)rff.getFormField(i)); + formField = ff.getFieldName(); + boolean isMultiValue = false; + isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX) + || ff.getFieldType().equals(FormField.FFT_LIST_MULTI); + boolean isTextArea = (ff.getFieldType().equals(FormField.FFT_TEXTAREA) && rr.getReportDefType() + .equals(AppConstants.RD_SQL_BASED)); + + if(request.getParameterValues(formField) != null && isMultiValue ) { + String[] vals = request.getParameterValues(formField); + StringBuffer value = new StringBuffer(""); + if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) { + + if ( isMultiValue ) { + value.append("("); + } + for(int j = 0 ; j < vals.length; j++) { + if(isMultiValue) value.append("'"); + try { + if(vals[j] !=null && vals[j].length() > 0) { + vals[j] = Utils.oracleSafe(vals[j]); + value.append(java.net.URLDecoder.decode(vals[j], "UTF-8"));// + ","; + } + else + value.append(vals[j]); + } catch (UnsupportedEncodingException ex) {value.append(vals[j]);} + catch (IllegalArgumentException ex1){value.append(vals[j]);} + catch (Exception ex2){ + value.append(vals[j]); + } + + + if(isMultiValue) value.append("'"); + + if(j != vals.length -1) { + value.append(","); + } + } + if(vals.length > 0) { + value.append(")"); + } + } + + //value = value.substring(0 , value.length()); + + valuesMap.put(fieldNameMap.get(formField), value.toString()); + value = new StringBuffer(""); + } else if(request.getParameter(formField) != null) { + if(isTextArea) { + String value = ""; + value = request.getParameter(formField); + + value = Utils.oracleSafe(value); + value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; + value = Utils.replaceInString(value, "|", ","); + valuesMap.put(fieldNameMap.get(formField), value); + value = ""; + } else { + String value = ""; + if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) + value = request.getParameter(formField); + valuesMap.put(fieldNameMap.get(formField), Utils.oracleSafe(value)); + } + + } else { + valuesMap.put(fieldNameMap.get(formField), "" ); + } + + } + + return valuesMap; + + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSON.java new file mode 100644 index 00000000..c03fb7ae --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSON.java @@ -0,0 +1,451 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +import java.util.ArrayList; +import java.util.Map; + +import org.openecomp.portalsdk.analytics.view.ColumnHeader; + +class Row { + private String displayValue; + private String dataType; + private String colId; + //private boolean visible; + + + /*public boolean isVisible() { + return visible; + } + public void setVisible(boolean visible) { + this.visible = visible; + }*/ + public String getDisplayValue() { + return displayValue; + } + public void setDisplayValue(String displayValue) { + this.displayValue = displayValue; + } + public String getDataType() { + return dataType; + } + public void setDataType(String dataType) { + this.dataType = dataType; + } + public String getColId() { + return colId; + } + public void setColId(String colId) { + this.colId = colId; + } + + +} +class IndexValueJSON { + private int index; + private String value; + private String title; + public int getIndex() { + return index; + } + public void setIndex(int index) { + this.index = index; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + +} + +class DomainAxisJSON extends IndexValueJSON {} + +class ChartColumnJSON extends IndexValueJSON {} + +class ChartTypeJSON extends IndexValueJSON {} + +class PieChartOptions { + +} + +public class ChartJSON { + + private String reportID; + private String reportName; + private String reportDescr; + private String reportTitle; + private String reportSubTitle; + private ArrayList formFieldList; + private ArrayList chartColumnJSONList; + private String formfield_comments; + private int totalRows; + private String chartSqlWhole; + private boolean chartAvailable; + private ChartTypeJSON chartTypeJSON; + private BarChartOptions barChartOptions; + private PieChartOptions pieChartOptions; + private TimeSeriesChartOptions timeSeriesChartOptions; + private FlexTimeSeriesChartOptions flexTimeSeriesChartOptions; + private CommonChartOptions commonChartOptions; + private String width; + private String height; + private boolean animation; + private String rotateLabels; + private boolean staggerLabels; + private boolean showTitle; + private DomainAxisJSON domainAxisJSON; + private CategoryAxisJSON categoryAxisJSON; + private boolean hasCategoryAxis; + + + public boolean isHasCategoryAxis() { + return hasCategoryAxis; + } + public void setHasCategoryAxis(boolean hasCategoryAxis) { + this.hasCategoryAxis = hasCategoryAxis; + } + private ArrayList rangeAxisList; + private ArrayList > wholeList; + + private String primaryAxisLabel; + private String secondaryAxisLabel; + private String minRange; + private String maxRange; + //private int topMargin; + //private int bottomMargin; + //private int leftMargin; + //private int rightMargin; + + /*private boolean showMaxMin; + private boolean showLegend; + private boolean showControls; + private String topMargin; + private String bottomMargin; + private String leftMargin; + private String rightMargin; + private String subType; + private boolean stacked; + private boolean horizontalBar; + private boolean barRealTimeAxis; + private boolean barReduceXAxisLabels; + private boolean timeAxis;*/ + + public String getReportID() { + return reportID; + } + public void setReportID(String reportID) { + this.reportID = reportID; + } + public String getReportName() { + return reportName; + } + public void setReportName(String reportName) { + this.reportName = reportName; + } + public String getReportDescr() { + return reportDescr; + } + public void setReportDescr(String reportDescr) { + this.reportDescr = reportDescr; + } + public String getReportTitle() { + return reportTitle; + } + public void setReportTitle(String reportTitle) { + this.reportTitle = reportTitle; + } + public String getReportSubTitle() { + return reportSubTitle; + } + public void setReportSubTitle(String reportSubTitle) { + this.reportSubTitle = reportSubTitle; + } + public ArrayList getFormFieldList() { + return formFieldList; + } + public void setFormFieldList(ArrayList formFieldList) { + this.formFieldList = formFieldList; + } + public String getFormfield_comments() { + return formfield_comments; + } + public void setFormfield_comments(String formfield_comments) { + this.formfield_comments = formfield_comments; + } + public int getTotalRows() { + return totalRows; + } + public void setTotalRows(int totalRows) { + this.totalRows = totalRows; + } + public String getChartSqlWhole() { + return chartSqlWhole; + } + public void setChartSqlWhole(String chartSqlWhole) { + this.chartSqlWhole = chartSqlWhole; + } + public boolean isChartAvailable() { + return chartAvailable; + } + public void setChartAvailable(boolean chartAvailable) { + this.chartAvailable = chartAvailable; + } + public String getWidth() { + return width; + } + public void setWidth(String width) { + this.width = width; + } + public String getHeight() { + return height; + } + public void setHeight(String height) { + this.height = height; + } + public boolean isAnimation() { + return animation; + } + public void setAnimation(boolean animation) { + this.animation = animation; + } + public String getRotateLabels() { + return rotateLabels; + } + public void setRotateLabels(String rotateLabels) { + this.rotateLabels = rotateLabels; + } + public boolean isStaggerLabels() { + return staggerLabels; + } + public void setStaggerLabels(boolean staggerLabels) { + this.staggerLabels = staggerLabels; + } + public boolean isShowTitle() { + return showTitle; + } + public void setShowTitle(boolean showTitle) { + this.showTitle = showTitle; + } + /*public boolean isShowMaxMin() { + return showMaxMin; + } + public void setShowMaxMin(boolean showMaxMin) { + this.showMaxMin = showMaxMin; + } + public boolean isShowLegend() { + return showLegend; + } + public void setShowLegend(boolean showLegend) { + this.showLegend = showLegend; + } + public boolean isShowControls() { + return showControls; + } + public void setShowControls(boolean showControls) { + this.showControls = showControls; + } + public String getTopMargin() { + return topMargin; + } + public void setTopMargin(String topMargin) { + this.topMargin = topMargin; + } + public String getBottomMargin() { + return bottomMargin; + } + public void setBottomMargin(String bottomMargin) { + this.bottomMargin = bottomMargin; + } + public String getLeftMargin() { + return leftMargin; + } + public void setLeftMargin(String leftMargin) { + this.leftMargin = leftMargin; + } + public String getRightMargin() { + return rightMargin; + } + public void setRightMargin(String rightMargin) { + this.rightMargin = rightMargin; + } + + public String getSubType() { + return subType; + } + public void setSubType(String subType) { + this.subType = subType; + } + public boolean isStacked() { + return stacked; + } + public void setStacked(boolean stacked) { + this.stacked = stacked; + } + public boolean isHorizontalBar() { + return horizontalBar; + } + public void setHorizontalBar(boolean horizontalBar) { + this.horizontalBar = horizontalBar; + } + public boolean isBarRealTimeAxis() { + return barRealTimeAxis; + } + public void setBarRealTimeAxis(boolean barRealTimeAxis) { + this.barRealTimeAxis = barRealTimeAxis; + } + public boolean isBarReduceXAxisLabels() { + return barReduceXAxisLabels; + } + public void setBarReduceXAxisLabels(boolean barReduceXAxisLabels) { + this.barReduceXAxisLabels = barReduceXAxisLabels; + } + public boolean isTimeAxis() { + return timeAxis; + } + public void setTimeAxis(boolean timeAxis) { + this.timeAxis = timeAxis; + }*/ + public ChartTypeJSON getChartTypeJSON() { + return chartTypeJSON; + } + public void setChartTypeJSON(ChartTypeJSON chartTypeJSON) { + this.chartTypeJSON = chartTypeJSON; + } + public String getChartType() { + return chartTypeJSON.getValue(); + } + public DomainAxisJSON getDomainAxisJSON() { + return domainAxisJSON; + } + public void setDomainAxisJSON(DomainAxisJSON domainAxisJSON) { + this.domainAxisJSON = domainAxisJSON; + } + public CategoryAxisJSON getCategoryAxisJSON() { + return categoryAxisJSON; + } + public void setCategoryAxisJSON(CategoryAxisJSON categoryAxisJSON) { + this.categoryAxisJSON = categoryAxisJSON; + } + public ArrayList getRangeAxisList() { + return rangeAxisList; + } + public void setRangeAxisList(ArrayList rangeAxisList) { + this.rangeAxisList = rangeAxisList; + } + public String getPrimaryAxisLabel() { + return primaryAxisLabel; + } + public void setPrimaryAxisLabel(String primaryAxisLabel) { + this.primaryAxisLabel = primaryAxisLabel; + } + public String getSecondaryAxisLabel() { + return secondaryAxisLabel; + } + public void setSecondaryAxisLabel(String secondaryAxisLabel) { + this.secondaryAxisLabel = secondaryAxisLabel; + } + public String getMinRange() { + return minRange; + } + public void setMinRange(String minRange) { + this.minRange = minRange; + } + public String getMaxRange() { + return maxRange; + } + public void setMaxRange(String maxRange) { + this.maxRange = maxRange; + } + /*public ArrayList getRowList() { + return rowList; + } + public void setRowList(ArrayList rowList) { + this.rowList = rowList; + }*/ + + public ArrayList> getWholeList() { + return wholeList; + } + public void setWholeList(ArrayList> wholeList) { + this.wholeList = wholeList; + } + //private ArrayList reportDataColumns; + //private ArrayList> reportDataRows; + public ArrayList getChartColumnJSONList() { + return chartColumnJSONList; + } + public void setChartColumnJSONList(ArrayList chartColumnJSONList) { + this.chartColumnJSONList = chartColumnJSONList; + } + + public BarChartOptions getBarChartOptions() { + return barChartOptions; + } + public void setBarChartOptions(BarChartOptions barChartOptions) { + this.barChartOptions = barChartOptions; + } + public PieChartOptions getPieChartOptions() { + return pieChartOptions; + } + public void setPieChartOptions(PieChartOptions pieChartOptions) { + this.pieChartOptions = pieChartOptions; + } + public TimeSeriesChartOptions getTimeSeriesChartOptions() { + return timeSeriesChartOptions; + } + public void setTimeSeriesChartOptions(TimeSeriesChartOptions timeSeriesChartOptions) { + this.timeSeriesChartOptions = timeSeriesChartOptions; + } + public FlexTimeSeriesChartOptions getFlexTimeSeriesChartOptions() { + return flexTimeSeriesChartOptions; + } + public void setFlexTimeSeriesChartOptions(FlexTimeSeriesChartOptions flexTimeSeriesChartOptions) { + this.flexTimeSeriesChartOptions = flexTimeSeriesChartOptions; + } + public CommonChartOptions getCommonChartOptions() { + return commonChartOptions; + } + public void setCommonChartOptions(CommonChartOptions commonChartOptions) { + this.commonChartOptions = commonChartOptions; + } + + public String getDomainAxis() { + if(getDomainAxisJSON() !=null) + return getDomainAxisJSON().getValue(); + else + return ""; + } + + public String getCategoryAxis() { + if(getCategoryAxisJSON()!=null) + return getCategoryAxisJSON().getValue(); + else + return ""; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSONHelper.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSONHelper.java new file mode 100644 index 00000000..d08626c1 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartJSONHelper.java @@ -0,0 +1,1550 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +import java.io.UnsupportedEncodingException; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.ReportHandler; +import org.openecomp.portalsdk.analytics.model.base.ChartSeqComparator; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.system.ConnectionUtils; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.util.DataSet; +import org.openecomp.portalsdk.analytics.util.Utils; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; +import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.web.support.UserUtils; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + + + +public class ChartJSONHelper { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChartJSONHelper.class); + + private ReportRuntime reportRuntime; + private String chartType; + + public static final long HOUR = 3600*1000; + public static final long DAY = 3600*1000*24; + public static final long MONTH = 3600*1000*24*31; + public static final long YEAR = 3600*1000*24*365; + + + public ChartJSONHelper() { + + } + + /** + * @return the chartType + */ + public String getChartType() { + return chartType; + } + + /** + * @param chartType the chartType to set + */ + public void setChartType(String chartType) { + this.chartType = chartType; + } + + public ChartJSONHelper(ReportRuntime rr) { + this.reportRuntime = rr; + } + + public String generateJSON(String reportID, HttpServletRequest request, boolean showData) throws RaptorException { + //From annotations chart + clearReportRuntimeBackup(request); + + //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); + final Long user_id = new Long((long) UserUtils.getUserId(request)); + //String action = request.getParameter(AppConstants.RI_ACTION); + //String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + + ReportHandler rh = new ReportHandler(); + //ReportData reportData = null; + HashMap chartOptionsMap = new HashMap(); + try { + if(reportID !=null) { + reportRuntime = rh.loadReportRuntime(request, reportID, true, 1); + setChartType(reportRuntime.getChartType()); + //reportData = reportRuntime.loadReportData(0, user_id.toString(), 10000,request, false); + } + + + + String rotateLabelsStr = ""; + rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle()); + if(rotateLabelsStr.toLowerCase().equals("standard")) { + rotateLabelsStr = "0"; + } else if (rotateLabelsStr.toLowerCase().equals("up45")) { + rotateLabelsStr = "45"; + } else if (rotateLabelsStr.toLowerCase().equals("down45")) { + rotateLabelsStr = "-45"; + } else if (rotateLabelsStr.toLowerCase().equals("up90")) { + rotateLabelsStr = "90"; + } else if (rotateLabelsStr.toLowerCase().equals("down90")) { + rotateLabelsStr = "-90"; + } else + rotateLabelsStr = "0"; + + String width = (AppUtils.getRequestNvlValue(request, "width").length()>0?AppUtils.getRequestNvlValue(request, "width"):(AppUtils.nvl(reportRuntime.getChartWidth()).length()>0?reportRuntime.getChartWidth():"700")); + String height = (AppUtils.getRequestNvlValue(request, "height").length()>0?AppUtils.getRequestNvlValue(request, "height"):(AppUtils.nvl(reportRuntime.getChartHeight()).length()>0?reportRuntime.getChartHeight():"300")); + String animationStr = (AppUtils.getRequestNvlValue(request, "animation").length()>0?AppUtils.getRequestNvlValue(request, "animation"):new Boolean(reportRuntime.isAnimateAnimatedChart()).toString()); + + String rotateLabels = (AppUtils.getRequestNvlValue(request, "rotateLabels").length()>0?AppUtils.getRequestNvlValue(request, "rotateLabels"):(rotateLabelsStr.length()>0?rotateLabelsStr:"0")); + String staggerLabelsStr = (AppUtils.getRequestNvlValue(request, "staggerLabels").length()>0?AppUtils.getRequestNvlValue(request, "staggerLabels"):"false"); + String showMaxMinStr = (AppUtils.getRequestNvlValue(request, "showMaxMin").length()>0?AppUtils.getRequestNvlValue(request, "showMaxMin"):"false"); + String showControlsStr = (AppUtils.getRequestNvlValue(request, "showControls").length()>0?AppUtils.getRequestNvlValue(request, "showControls"):new Boolean(reportRuntime.displayBarControls()).toString()); + String showLegendStr = (AppUtils.getRequestNvlValue(request, "showLegend").length()>0?AppUtils.getRequestNvlValue(request, "showLegend"):new Boolean(!new Boolean(reportRuntime.hideChartLegend())).toString()); + String topMarginStr = AppUtils.getRequestNvlValue(request, "topMargin"); + String topMargin = (AppUtils.nvl(topMarginStr).length()<=0)?(reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30"):topMarginStr; + String bottomMarginStr = AppUtils.getRequestNvlValue(request, "bottomMargin"); + String bottomMargin = (AppUtils.nvl(bottomMarginStr).length()<=0)?(reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50"):bottomMarginStr; + String leftMarginStr = AppUtils.getRequestNvlValue(request, "leftMargin"); + String leftMargin = (AppUtils.nvl(leftMarginStr).length()<=0)?(reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100"):leftMarginStr; + String rightMarginStr = AppUtils.getRequestNvlValue(request, "rightMargin"); + String rightMargin = (AppUtils.nvl(rightMarginStr).length()<=0)?(reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160"):rightMarginStr; + String showTitleStr = (AppUtils.getRequestNvlValue(request, "showTitle").length()>0?AppUtils.getRequestNvlValue(request, "showTitle"):new Boolean(reportRuntime.displayChartTitle()).toString()); + String subType = AppUtils.getRequestNvlValue(request, "subType").length()>0?AppUtils.getRequestNvlValue(request, "subType"):(AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():""); + String stackedStr = AppUtils.getRequestNvlValue(request, "stacked").length()>0?AppUtils.getRequestNvlValue(request, "stacked"):new Boolean(reportRuntime.isChartStacked()).toString(); + String horizontalBar = AppUtils.getRequestNvlValue(request, "horizontalBar").length()>0?AppUtils.getRequestNvlValue(request, "horizontalBar"):new Boolean(reportRuntime.isHorizontalOrientation()).toString(); + String barRealTimeAxis = AppUtils.getRequestNvlValue(request, "barRealTimeAxis"); + String barReduceXAxisLabels = AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels").length()>0?AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels"):new Boolean(reportRuntime.isLessXaxisTickers()).toString();; + String timeAxis = AppUtils.getRequestNvlValue(request, "timeAxis").length()>0?AppUtils.getRequestNvlValue(request, "timeAxis"):new Boolean(reportRuntime.isTimeAxis()).toString(); + String logScale = AppUtils.getRequestNvlValue(request, "logScale").length()>0?AppUtils.getRequestNvlValue(request, "logScale"):new Boolean(reportRuntime.isLogScale()).toString(); + String precision = AppUtils.getRequestNvlValue(request, "precision").length()>0?AppUtils.getRequestNvlValue(request, "precision"):"2"; + + + chartOptionsMap.put("width", width); + chartOptionsMap.put("height", height); + chartOptionsMap.put("animation", animationStr); + chartOptionsMap.put("rotateLabels", rotateLabels); + chartOptionsMap.put("staggerLabels", staggerLabelsStr); + chartOptionsMap.put("showMaxMin", showMaxMinStr); + chartOptionsMap.put("showControls", showControlsStr); + chartOptionsMap.put("showLegend", showLegendStr); + chartOptionsMap.put("topMargin", topMargin); + chartOptionsMap.put("bottomMargin", bottomMargin); + chartOptionsMap.put("leftMargin", leftMargin); + chartOptionsMap.put("rightMargin", rightMargin); + chartOptionsMap.put("showTitle", showTitleStr); + chartOptionsMap.put("subType", subType); + chartOptionsMap.put("stacked", stackedStr); + chartOptionsMap.put("horizontalBar", horizontalBar); + chartOptionsMap.put("timeAxis", timeAxis); + chartOptionsMap.put("barRealTimeAxis", barRealTimeAxis); + chartOptionsMap.put("barReduceXAxisLabels", barReduceXAxisLabels); + + chartOptionsMap.put("logScale", logScale); + chartOptionsMap.put("precision", precision); + + + } catch (RaptorException ex) { + ex.printStackTrace(); + } + return generateJSON(reportRuntime, chartOptionsMap, request, showData); + } + + public String generateJSON(ReportRuntime reportRuntime, HttpServletRequest request, boolean showData) throws RaptorException { + + String rotateLabelsStr = ""; + rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle()); + if(rotateLabelsStr.toLowerCase().equals("standard")) { + rotateLabelsStr = "0"; + } else if (rotateLabelsStr.toLowerCase().equals("up45")) { + rotateLabelsStr = "45"; + } else if (rotateLabelsStr.toLowerCase().equals("down45")) { + rotateLabelsStr = "-45"; + } else if (rotateLabelsStr.toLowerCase().equals("up90")) { + rotateLabelsStr = "90"; + } else if (rotateLabelsStr.toLowerCase().equals("down90")) { + rotateLabelsStr = "-90"; + } else + rotateLabelsStr = "0"; + + HashMap chartOptionsMap = new HashMap(); + chartOptionsMap.put("width", reportRuntime.getChartWidth()); + chartOptionsMap.put("height", reportRuntime.getChartHeight()); + chartOptionsMap.put("animation", new Boolean(reportRuntime.isAnimateAnimatedChart()).toString()); + chartOptionsMap.put("rotateLabels", rotateLabelsStr); + chartOptionsMap.put("staggerLabels", "false"); + chartOptionsMap.put("showMaxMin", "false"); + chartOptionsMap.put("showControls", new Boolean(reportRuntime.displayBarControls()).toString()); + chartOptionsMap.put("showLegend", new Boolean(!reportRuntime.hideChartLegend()).toString()); + chartOptionsMap.put("topMargin", reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30"); + chartOptionsMap.put("bottomMargin", reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50"); + chartOptionsMap.put("leftMargin", reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100"); + chartOptionsMap.put("rightMargin", reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160"); + chartOptionsMap.put("showTitle", new Boolean(reportRuntime.displayChartTitle()).toString()); + chartOptionsMap.put("subType", (AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():"")); + chartOptionsMap.put("stacked", new Boolean(reportRuntime.isChartStacked()).toString()); + chartOptionsMap.put("horizontalBar", new Boolean(reportRuntime.isHorizontalOrientation()).toString()); + chartOptionsMap.put("timeAxis", new Boolean(reportRuntime.isTimeAxis()).toString()); + chartOptionsMap.put("barReduceXAxisLabels", new Boolean(reportRuntime.isLessXaxisTickers()).toString()); + + chartOptionsMap.put("logScale", new Boolean(reportRuntime.isLogScale()).toString()); + chartOptionsMap.put("precision", "2"); + + + + return generateJSON(reportRuntime, chartOptionsMap, request, showData); + } + + public String generateJSON(ReportRuntime reportRuntime, HashMap chartOptionsMap, HttpServletRequest request, boolean showData) throws RaptorException { + + //String width, String height, boolean animation, String rotateLabels, boolean staggerLabels, boolean showMaxMin, boolean showLegend, boolean showControls, String topMargin, String bottomMargin, boolean showTitle, String subType + String userId = AppUtils.getUserID(request); + String width = chartOptionsMap.get("width"); + String height = chartOptionsMap.get("height"); + boolean animation = getBooleanValue(chartOptionsMap.get("animation"), true); + String rotateLabels = chartOptionsMap.get("rotateLabels"); + boolean staggerLabels = getBooleanValue(chartOptionsMap.get("staggerLabels")); + boolean showMaxMin = getBooleanValue(chartOptionsMap.get("showMaxMin"), false); + boolean showLegend = getBooleanValue(chartOptionsMap.get("showLegend"), true); + boolean showControls = getBooleanValue(chartOptionsMap.get("showControls"), true); + String topMargin = chartOptionsMap.get("topMargin"); + String bottomMargin = chartOptionsMap.get("bottomMargin"); + String leftMargin = chartOptionsMap.get("leftMargin"); + String rightMargin = chartOptionsMap.get("rightMargin"); + boolean showTitle = getBooleanValue(chartOptionsMap.get("showTitle"), true); + String subType = chartOptionsMap.get("subType"); + boolean stacked = getBooleanValue(chartOptionsMap.get("stacked"), false); + boolean horizontalBar = getBooleanValue(chartOptionsMap.get("horizontalBar"), false); + boolean barRealTimeAxis = getBooleanValue(chartOptionsMap.get("barRealTimeAxis"), true); + boolean barReduceXAxisLabels= getBooleanValue(chartOptionsMap.get("barReduceXAxisLabels"), false); + boolean timeAxis = getBooleanValue(chartOptionsMap.get("timeAxis"), true); + + + boolean logScale = getBooleanValue(chartOptionsMap.get("logScale"), false); + + int precision = 2; + + try { + precision = Integer.parseInt(chartOptionsMap.get("precision")); + } catch (NumberFormatException ex) { + + } + + final Long user_id = new Long((long) UserUtils.getUserId(request)); + + HttpSession session = null; + session = request.getSession(); + String chartType = reportRuntime.getChartType(); + List l = reportRuntime.getAllColumns(); + List lGroups = reportRuntime.getAllChartGroups(); + HashMap mapYAxis = reportRuntime.getAllChartYAxis(reportRuntime.getReportParamValues()); + //ReportParamValues reportParamValues = reportRuntime.getReportParamValues(); + String chartLeftAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartLeftAxisLabel())); + String chartRightAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartRightAxisLabel())); + + boolean multipleSeries = reportRuntime.isMultiSeries(); + + java.util.HashMap formValues = null; + formValues = getRequestParametersMap(reportRuntime, request); + + + String legendColumnName = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():"Legend Column"; + boolean displayChart = reportRuntime.getDisplayChart(); + HashMap additionalChartOptionsMap = new HashMap(); + + StringBuffer wholeScript = new StringBuffer(""); + + String title = reportRuntime.getReportTitle(); + + title = parseTitle(title, formValues); + ObjectMapper mapper = new ObjectMapper(); + ChartJSON chartJSON = new ChartJSON(); + String sql = ""; + if(displayChart) { + DataSet ds = null; + if(showData) { + + try { + if (!(chartType.equals(AppConstants.GT_HIERARCHICAL) || chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST) || chartType.equals(AppConstants.GT_ANNOTATION_CHART))) { + sql = generateChartSQL(userId, request ); + ds = (DataSet) loadChartData(new Long(user_id).toString(), request); + } else if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) { + sql = reportRuntime.getWholeSQL(); + String reportSQL = reportRuntime.getWholeSQL(); + String dbInfo = reportRuntime.getDBInfo(); + ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); + if(ds.getRowCount()<=0) { + logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + logger.info(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY" )); + logger.info(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportSQL)); + logger.info(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + } + } else if(chartType.equals(AppConstants.GT_HIERARCHICAL)||chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) { + sql = reportRuntime.getWholeSQL(); + String reportSQL = reportRuntime.getWholeSQL(); + String dbInfo = reportRuntime.getDBInfo(); + ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); + } + } catch (RaptorException ex) { + //throw new RaptorException("Error while loading chart data", ex); + logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + logger.error(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " ERROR THROWN FOR GIVEN QUERY ")); + logger.error(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportRuntime.getWholeSQL())); + logger.error(EELFLoggerDelegate.debugLogger, ("ERROR STACK TRACE" + ex.getMessage())); + logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); + + } + if(ds==null) { + //displayChart = false; + if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) + ds = new DataSet(); + else + displayChart = false; + } + } + if(displayChart) { + + chartJSON.setReportID(reportRuntime.getReportID()); + chartJSON.setReportName(reportRuntime.getReportName()); + chartJSON.setReportDescr(reportRuntime.getReportDescr()); + chartJSON.setReportTitle(reportRuntime.getReportTitle()); + chartJSON.setReportSubTitle(reportRuntime.getReportSubTitle()); + + List dcList = reportRuntime.getOnlyVisibleColumns(); + int countIndex = 0; + ArrayList chartColumnJSONList = new ArrayList(); + for(Iterator iter = dcList.iterator(); iter.hasNext(); ) { + ChartColumnJSON ccJSON = new ChartColumnJSON(); + DataColumnType dc = (DataColumnType) iter.next(); + ccJSON.setIndex(countIndex); + ccJSON.setValue(dc.getColId()); + ccJSON.setTitle(dc.getDisplayName()); + countIndex++; + chartColumnJSONList.add(ccJSON); + } + chartJSON.setChartColumnJSONList(chartColumnJSONList); + /* setting formfields show only showForm got triggered*/ + /*ArrayList formFieldValues = new ArrayList(); + ArrayList formFieldJSONList = new ArrayList(); + if(reportRuntime.getReportFormFields()!=null) { + formFieldJSONList = new ArrayList(reportRuntime.getReportFormFields().size()); + for (Iterator iter = reportRuntime.getReportFormFields().iterator(); iter.hasNext();) { + formFieldValues = new ArrayList(); + FormField ff = (FormField) iter.next(); + ff.setDbInfo(reportRuntime.getDbInfo()); + FormFieldJSON ffJSON = new FormFieldJSON(); + ffJSON.setFieldId(ff.getFieldName()); + ffJSON.setFieldType(ff.getFieldType()); + ffJSON.setFieldDisplayName(ff.getFieldDisplayName()); + ffJSON.setHelpText(ff.getHelpText()); + ffJSON.setValidationType(ff.getValidationType()); + //ffJSON.setTriggerOtherFormFields(ff.getDependsOn()); + IdNameList lookup = null; + lookup = ff.getLookupList(); + String selectedValue = ""; + String oldSQL = ""; + IdNameList lookupList = null; + boolean readOnly = false; + if(lookup!=null) { + if(!ff.hasPredefinedList) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = lu.getSql(); + oldSQL = lu.getSql(); + reportRuntime.setTriggerFormFieldCheck( reportRuntime.getReportFormFields(), ff); + ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields()); + SQL = reportRuntime.parseAndFillReq_Session_UserValues(request, SQL, userId); + SQL = reportRuntime.parseAndFillWithCurrentValues(request, SQL, ff); + String defaultSQL = lu.getDefaultSQL(); + defaultSQL = reportRuntime.parseAndFillReq_Session_UserValues(request, defaultSQL, userId); + defaultSQL = reportRuntime.parseAndFillWithCurrentValues(request, SQL, ff); + lookup = new IdNameSql(-1,SQL,defaultSQL); + + lookupList = lookup; + try { + lookup.loadUserData(0, "", ff.getDbInfo(), ff.getUserId()); + } catch (Exception e ){ e.printStackTrace(); //throw new RaptorRuntimeException(e); + } + } + lookup.trimToSize(); + + String[] requestValue = request.getParameterValues(ff.getFieldName()); + + if(lookup != null && lookup.size() > 0) { + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + readOnly = value.isReadOnly(); + if(requestValue != null && Arrays.asList(requestValue).contains(value.getId())) { + //if(value.getId().equals(requestValue)) + value.setDefaultValue(true); + } + if(!(ff.getFieldType().equals(FormField.FFT_CHECK_BOX) || ff.getFieldType().equals(FormField.FFT_COMBO_BOX) || ff.getFieldType().equals(FormField.FFT_LIST_BOX) + || ff.getFieldType().equals(FormField.FFT_LIST_MULTI)) && value.isDefaultValue()) + formFieldValues.add(value); + else if(ff.getFieldType().equals(FormField.FFT_CHECK_BOX) || ff.getFieldType().equals(FormField.FFT_COMBO_BOX) || ff.getFieldType().equals(FormField.FFT_LIST_BOX) + || ff.getFieldType().equals(FormField.FFT_LIST_MULTI)) { + formFieldValues.add(value); + } + //break; + } + } else { + if(requestValue!=null && requestValue.length>0) { + IdNameValue value = new IdNameValue(requestValue[0], requestValue[0], true, false); + formFieldValues.add(value); + } + } + + } else { + String[] requestValue = request.getParameterValues(ff.getFieldName()); + if(requestValue!=null && requestValue.length>0) { + IdNameValue value = new IdNameValue(requestValue[0], requestValue[0], true, false); + formFieldValues.add(value); + } + } + if(!ff.hasPredefinedList) { + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + } + + + + ffJSON.setFormFieldValues(formFieldValues); + formFieldJSONList.add(ffJSON); + } // for + } + chartJSON.setFormFieldList(formFieldJSONList); + chartJSON.setChartSqlWhole(sql);*/ + chartJSON.setChartAvailable(displayChart); + + ChartTypeJSON chartTypeJSON = new ChartTypeJSON(); + chartTypeJSON.setIndex(0); + chartTypeJSON.setTitle(""); + chartTypeJSON.setValue(chartType); + chartJSON.setChartTypeJSON(chartTypeJSON); + chartJSON.setWidth(width); + chartJSON.setHeight(height); + chartJSON.setAnimation(animation); + chartJSON.setRotateLabels(rotateLabels); + chartJSON.setStaggerLabels(staggerLabels); + chartJSON.setShowTitle(showTitle); + DomainAxisJSON domainAxisJSON = new DomainAxisJSON(); + domainAxisJSON.setIndex(0); + if(reportRuntime.getChartLegendColumn()!=null) + domainAxisJSON.setTitle(reportRuntime.getChartLegendColumn().getDisplayName()); + else + domainAxisJSON.setTitle(""); + if(reportRuntime.getChartLegendColumn()!=null) + domainAxisJSON.setValue(reportRuntime.getChartLegendColumn().getColId()); + else + domainAxisJSON.setValue(""); + chartJSON.setDomainAxisJSON(domainAxisJSON); + + + List reportCols = reportRuntime.getAllColumns(); + boolean hasSeriesColumn = false; + //ArrayList + for (Iterator iter = reportCols.iterator(); iter + .hasNext();) { + DataColumnType dct = (DataColumnType) iter.next(); + if(dct.isChartSeries()!=null && dct.isChartSeries().booleanValue()) { + chartJSON.setHasCategoryAxis(true); + CategoryAxisJSON categoryAxisJSON = new CategoryAxisJSON(); + categoryAxisJSON.setIndex(0); + categoryAxisJSON.setTitle(dct.getDisplayName()); + categoryAxisJSON.setValue(dct.getColId()); + chartJSON.setCategoryAxisJSON(categoryAxisJSON); + } + //allColumns + //.add(new Item(dct.getColId(), dct.getDisplayName())); + } + //chartJSON.setCategoryAxis(categoryAxis); + //chartJSON.set + + List chartValueCols = reportRuntime.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); + DataColumnType dct_RangeAxis = null; + //int noChart = 0; + //if(chartValueCols.size()<=0) { + //chartValueCols.addAll(reportCols); + //noChart = 1; + //} + if(chartValueCols.size() <= 0) { + chartValueCols = reportCols; + } + ArrayList rangeAxisJSONList = new ArrayList(); + for (int k = 0; k < chartValueCols.size(); k++) { + dct_RangeAxis = chartValueCols.get(k); + RangeAxisJSON rangeAxisJSON = new RangeAxisJSON(); + + RangeAxisLabelJSON rangeAxisLabelJSON = new RangeAxisLabelJSON(); + rangeAxisLabelJSON.setIndex(0); + rangeAxisLabelJSON.setTitle(dct_RangeAxis.getDisplayName()); + rangeAxisLabelJSON.setValue(dct_RangeAxis.getColId()); + rangeAxisJSON.setRangeAxisLabelJSON(rangeAxisLabelJSON); + RangeLineTypeJSON rangeLineTypeJSON = new RangeLineTypeJSON(); + rangeLineTypeJSON.setIndex(0); + rangeLineTypeJSON.setTitle(""); + rangeLineTypeJSON.setValue(dct_RangeAxis.getChartLineType()); + rangeAxisJSON.setRangeLineTypeJSON(rangeLineTypeJSON); + + RangeColorJSON rangeColorJSON = new RangeColorJSON(); + rangeColorJSON.setIndex(0); + rangeColorJSON.setTitle(""); + rangeColorJSON.setValue(dct_RangeAxis.getChartColor()); + rangeAxisJSON.setRangeColorJSON(rangeColorJSON); + String chartGroup = ""; + chartGroup = AppUtils.nvl(dct_RangeAxis.getChartGroup()); + if(chartGroup.indexOf("|")!=-1) + chartGroup = chartGroup.substring(0, chartGroup.indexOf("|")); + + + rangeAxisJSON.setRangeChartGroup(chartGroup); + String yAxis = ""; + yAxis = AppUtils.nvl(dct_RangeAxis.getYAxis()); + if(yAxis.indexOf("|")!=-1) + yAxis = yAxis.substring(0, yAxis.indexOf("|")); + + rangeAxisJSON.setRangeYAxis(yAxis); + rangeAxisJSON.setShowAsArea((dct_RangeAxis.isIsRangeAxisFilled()!=null && dct_RangeAxis.isIsRangeAxisFilled().booleanValue())?true:false); + rangeAxisJSONList.add(rangeAxisJSON); + } + CommonChartOptions commonChartOptions = new CommonChartOptions(); + commonChartOptions.setLegendPosition(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>0?reportRuntime.getLegendPosition().toLowerCase():"top"); + String legendLabelAngle = ""; + legendLabelAngle = reportRuntime.getLegendLabelAngle().toLowerCase(); + commonChartOptions.setLegendLabelAngle(AppUtils.nvl(legendLabelAngle).length()>0?legendLabelAngle:"up45"); + commonChartOptions.setHideLegend(reportRuntime.hideChartLegend()); + commonChartOptions.setAnimateAnimatedChart(reportRuntime.isAnimateAnimatedChart()); + commonChartOptions.setTopMargin(reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin():new Integer("30")); + commonChartOptions.setBottomMargin(reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin():new Integer("50")); + commonChartOptions.setLeftMargin(reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin():new Integer("100")); + commonChartOptions.setRightMargin(reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin():new Integer("60")); + chartJSON.setCommonChartOptions(commonChartOptions); + + if(chartType.equals(AppConstants.GT_BAR_3D)) { + BarChartOptions barChartOptions = new BarChartOptions(); + barChartOptions.setDisplayBarControls(reportRuntime.displayBarControls()?true:false); + barChartOptions.setMinimizeXAxisTickers(reportRuntime.isLessXaxisTickers()?true:false); + barChartOptions.setStackedChart(reportRuntime.isChartStacked()?true:false); + barChartOptions.setTimeAxis(reportRuntime.isTimeAxis()?true:false); + barChartOptions.setVerticalOrientation(reportRuntime.isVerticalOrientation()?true:false); + barChartOptions.setxAxisDateType(reportRuntime.isXAxisDateType()?true:false); + barChartOptions.setyAxisLogScale(reportRuntime.isLogScale()?true:false); + chartJSON.setBarChartOptions(barChartOptions); + chartJSON.setTimeSeriesChartOptions(null); + chartJSON.setPieChartOptions(null); + chartJSON.setFlexTimeSeriesChartOptions(null); + + } else if(chartType.equals(AppConstants.GT_TIME_SERIES)) { + TimeSeriesChartOptions timeSeriesChartOptions = new TimeSeriesChartOptions(); + timeSeriesChartOptions.setAddXAxisTicker(reportRuntime.isAddXAxisTickers()); + timeSeriesChartOptions.setLineChartRenderer(AppUtils.nvl(reportRuntime.getTimeSeriesRender()).length()>0?reportRuntime.getTimeSeriesRender():"line"); + timeSeriesChartOptions.setMultiSeries(reportRuntime.isMultiSeries()); + timeSeriesChartOptions.setNonTimeAxis(reportRuntime.isTimeAxis()); + timeSeriesChartOptions.setShowXAxisLabel(reportRuntime.isShowXaxisLabel()); + chartJSON.setBarChartOptions(null); + chartJSON.setTimeSeriesChartOptions(timeSeriesChartOptions); + chartJSON.setPieChartOptions(null); + chartJSON.setFlexTimeSeriesChartOptions(null); + } else if(chartType.equals(AppConstants.GT_ANNOTATION_CHART) || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) { + FlexTimeSeriesChartOptions flexTimeSeriesChartOptions = new FlexTimeSeriesChartOptions(); + flexTimeSeriesChartOptions.setZoomIn(reportRuntime.getZoomIn()!=null?reportRuntime.getZoomIn():new Integer("25")); + String timeAxisTypeStr = ""; + timeAxisTypeStr = reportRuntime.getTimeAxisType().toLowerCase(); + flexTimeSeriesChartOptions.setTimeAxisType(timeAxisTypeStr); + chartJSON.setBarChartOptions(null); + chartJSON.setTimeSeriesChartOptions(null); + chartJSON.setPieChartOptions(null); + chartJSON.setFlexTimeSeriesChartOptions(flexTimeSeriesChartOptions); + } + chartJSON.setRangeAxisList(rangeAxisJSONList); + chartJSON.setPrimaryAxisLabel(reportRuntime.getChartLeftAxisLabel()); + chartJSON.setSecondaryAxisLabel(reportRuntime.getChartRightAxisLabel()); + chartJSON.setMinRange(reportRuntime.getRangeAxisLowerLimit()); + chartJSON.setMaxRange(reportRuntime.getRangeAxisUpperLimit()); + + if(showData) { + ArrayList> wholeList = new ArrayList>(); + + ArrayList rowList = new ArrayList(); + if(showData) { + for (int i = 0; i < ds.getRowCount(); i++) { + rowList = new ArrayList(); + for (int j = 0; j0) { + /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL"));*/ + reportSQL = Utils.replaceInString(reportSQL, fieldDisplay, nvl( + paramValue, "NULL")); + } + /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL"));*/ + reportSQL = Utils.replaceInString(reportSQL, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL")); + reportSQL = Utils.replaceInString(reportSQL, fieldDisplay , nvl( + paramValue, "NULL")); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL)); + String legendCol = "1 a"; + // String valueCol = "1"; + StringBuffer groupCol = new StringBuffer(); + StringBuffer seriesCol = new StringBuffer(); + StringBuffer valueCols = new StringBuffer(); + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, request); + if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + legendCol = getSelectExpr(dc, colName)+" " + dc.getColId(); + // if(dc.getChartSeq()>0) + // valueCol = "NVL("+colName+", 0) "+dc.getColId(); + if ((!nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) + && (dc.getChartSeq()!=null && dc.getChartSeq().intValue() <= 0) && dc.isGroupBreak()) { + groupCol.append(", "); + groupCol.append(colName + " " + dc.getColId()); + } + } // for + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(dc.isChartSeries()!=null && dc.isChartSeries().booleanValue()) { + //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); + seriesCol.append(", "+ getSelectExpr(dc,getColumnSelectStr(dc, request))+ " " + dc.getColId()); + } + } + + /*for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + if(!dc.isChartSeries() && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); + seriesCol.append(", "+ formatChartColumn(getSelectExpr(dc,getColumnSelectStr(dc, paramValues)))+ " " + dc.getColId()); + } + }*/ + + for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, request); + String paramValue = ""; + if(AppUtils.nvl(colName).startsWith("[")) { + if (reportRuntime.getFormFieldList() != null) { + for (Iterator iterC = reportRuntime.getFormFieldList().getFormField().iterator(); iterC.hasNext();) { + FormFieldType fft = (FormFieldType) iterC.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); + String formfield_value = ""; + if(AppUtils.nvl(fieldDisplay).equals(colName)) { + formfield_value = AppUtils.getRequestNvlValue(request, fieldId); + paramValue = nvl(formfield_value); + } + } + + } + + seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:"null") + " " + dc.getColId()); + } else { + //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); + seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:formatChartColumn(colName)) + " " + dc.getColId()); + } + } // for + + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = dc.getDisplayName(); + String colValue = getColumnSelectStr(dc, request); + //String colName = getColumnSelectStr(dc, formGrid); + if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) + seriesCol.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); + if (colName.equals(AppConstants.RI_CHART_COLOR)) + seriesCol.append(", " + colValue + " " + AppConstants.RI_CHART_COLOR ); + if(colName.equals(AppConstants.RI_CHART_MARKER_START)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_START + " " + AppConstants.RI_CHART_MARKER_START ); + if(colName.equals(AppConstants.RI_CHART_MARKER_END)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_END + " " + AppConstants.RI_CHART_MARKER_END ); + if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_LEFT)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_LEFT + " " + AppConstants.RI_CHART_MARKER_TEXT_LEFT ); + if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_RIGHT)) + seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT + " " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT ); + //if(colName.equals(AppConstants.RI_ANOMALY_TEXT)) + //seriesCol.append(", " + AppConstants.RI_ANOMALY_TEXT + " " + AppConstants.RI_ANOMALY_TEXT ); + } + + //debugLogger.debug("ReportSQL Chart " + reportSQL ); + /*for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); + valueCols.append("," + formatChartColumn(colName) + " " + dc.getColId()); + } // for + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + DataColumnType dc = (DataColumnType) iter.next(); + String colName = getColumnSelectStr(dc, paramValues); + //if(colName.equals(AppConstants.RI_CHART_TOTAL_COL) || colName.equals(AppConstants.RI_CHART_COLOR)) { + if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) + valueCols.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); + if (colName.equals(AppConstants.RI_CHART_COLOR)) + valueCols.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR ); + if (colName.equals(AppConstants.RI_CHART_INCLUDE)) + valueCols.append(", " + AppConstants.RI_CHART_INCLUDE + " " + AppConstants.RI_CHART_INCLUDE ); + //} + }*/ + String final_sql = ""; + reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM "); + reportSQL = Utils.replaceInString(reportSQL, " From ", " FROM "); + reportSQL = Utils.replaceInString(reportSQL, " select ", " SELECT "); + reportSQL = Utils.replaceInString(reportSQL, " union ", " UNION "); + //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); +// if(reportSQL.indexOf("UNION") != -1) { +// if(reportSQL.indexOf("FROM(")!=-1) +// final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM(") ); +// else if (reportSQL.indexOf("FROM (")!=-1) +// final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM (") ); +// //TODO ELSE THROW ERROR +// } +// else { +// final_sql += " "+reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM ")); +// } + int pos = 0; + int pos_first_select = 0; + int pos_dup_select = 0; + int pos_prev_select = 0; + int pos_last_select = 0; + if (reportSQL.indexOf("FROM", pos)!=-1) { + pos = reportSQL.indexOf("FROM", pos); + pos_dup_select = reportSQL.lastIndexOf("SELECT",pos); + pos_first_select = reportSQL.indexOf("SELECT");//,pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select)); + if(pos_dup_select > pos_first_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select)); + //pos_dup_select1 = pos_dup_select; + pos_prev_select = pos_first_select; + pos_last_select = pos_dup_select; + while (pos_last_select > pos_prev_select) { + logger.debug(EELFLoggerDelegate.debugLogger, ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select)); + pos = reportSQL.indexOf("FROM", pos+2); + pos_prev_select = pos_last_select; + pos_last_select = reportSQL.lastIndexOf("SELECT",pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select)); + } + } + + } + final_sql += " "+reportSQL.substring(pos); + logger.debug(EELFLoggerDelegate.debugLogger, ("Final SQL " + final_sql)); + String sql = "SELECT " + legendCol + ", " + legendCol+"_1" + seriesCol.toString()+ nvl(valueCols.toString(), ", 1") + + groupCol.toString() + + final_sql; + logger.debug(EELFLoggerDelegate.debugLogger, ("Final sql in generateChartSQL " +sql)); + + return sql; + } // generateChartSQL + + private String getColumnSelectStr(DataColumnType dc, HttpServletRequest request) { + //String colName = dc.isCalculated() ? dc.getColName() + // : ((nvl(dc.getTableId()).length() > 0) ? (dc.getTableId() + "." + dc + // .getColName()) : dc.getColName()); + String colName = dc.getColName(); + String paramValue = null; + //if (dc.isCalculated()) { + if (reportRuntime.getFormFieldList() != null) { + for (Iterator iter = reportRuntime.getFormFieldList().getFormField().iterator(); iter.hasNext();) { + FormFieldType fft = (FormFieldType) iter.next(); + String fieldId = fft.getFieldId(); + String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); + String formfield_value = ""; + formfield_value = AppUtils.getRequestNvlValue(request, fieldId); + paramValue = nvl(formfield_value); + if(paramValue.length()>0) { + /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( + paramValue, "NULL"));*/ + colName = Utils.replaceInString(colName, "'" + fieldDisplay + "'", "'"+nvl( + paramValue, "NULL")+"'"); + colName = Utils.replaceInString(colName, fieldDisplay, nvl( + paramValue, "NULL")); + } + } + return colName; + } + //} + return colName; + } // getColumnSelectStr + + + + public String getSelectExpr(DataColumnType dct) { + // String colName = + // dct.isCalculated()?dct.getColName():((nvl(dct.getTableId()).length()>0)?(dct.getTableId()+"."+dct.getColName()):dct.getColName()); + return getSelectExpr(dct, dct.getColName() /* colName */); + } // getSelectExpr + + private String getSelectExpr(DataColumnType dct, String colName) { + String colType = dct.getColType(); + if (colType.equals(AppConstants.CT_CHAR) + || ((nvl(dct.getColFormat()).length() == 0) && (!colType + .equals(AppConstants.CT_DATE)))) + return colName; + else + return "TO_CHAR(" + colName + ", '" + + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')"; + } // getSelectExpr + + private String formatChartColumn(String colName) { + logger.debug(EELFLoggerDelegate.debugLogger, ("Format Chart Column Input colName " + colName)); + colName = colName.trim(); + colName = Utils.replaceInString(colName, "TO_CHAR", "to_char"); + colName = Utils.replaceInString(colName, "to_number", "TO_NUMBER"); + //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); + colName = colName.replaceAll(",[\\s]*\\(", ",("); + StringBuffer colNameBuf = new StringBuffer(colName); + int pos = 0, posFormatStart = 0, posFormatEnd = 0; + String format = ""; + + if(colNameBuf.indexOf("999")==-1 && colNameBuf.indexOf("990")==-1) { + logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); + return colNameBuf.toString(); + } + + while (colNameBuf.indexOf("to_char")!=-1) { + if(colNameBuf.indexOf("999")!=-1 || colNameBuf.indexOf("990")!=-1) { + pos = colNameBuf.indexOf("to_char"); + colNameBuf.insert(pos, " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ("); + pos = colNameBuf.indexOf("to_char"); + colNameBuf.replace(pos, pos+7, "TO_CHAR"); + //colName = Utils.replaceInString(colNameBuf.toString(), "to_char", " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ( TO_CHAR "); + logger.debug(EELFLoggerDelegate.debugLogger, ("After adding to_number " + colNameBuf.toString())); + //posFormatStart = colNameBuf.lastIndexOf(",'")+1; + posFormatStart = colNameBuf.indexOf(",'", pos)+1; + posFormatEnd = colNameBuf.indexOf(")",posFormatStart); + logger.debug(EELFLoggerDelegate.debugLogger, (posFormatStart + " " + posFormatEnd + " "+ pos)); + format = colNameBuf.substring(posFormatStart, posFormatEnd); + //posFormatEnd = colNameBuf.indexOf(")",posFormatEnd); + colNameBuf.insert(posFormatEnd+1, " ," + format + ") , "+ format + ")"); + logger.debug(EELFLoggerDelegate.debugLogger, ("colNameBuf " + colNameBuf.toString())); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); + return colNameBuf.toString(); + } + + public List getChartValueColumnsList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ + List reportCols = reportRuntime.getAllColumns(); + + ArrayList chartValueCols = new ArrayList(); + int flag = 0; + for (Iterator iter = reportCols.iterator(); iter.hasNext();) { + flag = 0; + DataColumnType dc = (DataColumnType) iter.next(); +// if(filter == 2 || filter == 1) { + flag = reportRuntime.getDependsOnFormFieldFlag(dc, formValues); + + if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { + if(nvl(dc.getChartGroup()).length()<=0) { + if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { + chartValueCols.add(dc); + } + else if(filter == 0) chartValueCols.add(dc); + } else chartValueCols.add(dc); + } +// } else +// chartValueCols.add(dc); + } // for + Collections.sort(chartValueCols, new ChartSeqComparator()); + return chartValueCols; + } // getChartValueColumnsList + + public String parseTitle(String title, HashMap formValues) { + Set set = formValues.entrySet(); + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + if(title.indexOf("["+ entry.getKey() + "]")!= -1) { + title = Utils.replaceInString(title, "["+entry.getKey()+"]", nvl( + (String) entry.getValue(), "")); + } + } + return title; + } + + public java.util.Date getDateFromDateStr(String dateStr) { + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + SimpleDateFormat EEEMMDDYYYYFormat = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00 + SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); + SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat timestampHrFormat = new SimpleDateFormat("yyyy-MM-dd HH"); + SimpleDateFormat timestampDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + SimpleDateFormat MMDDYYYYHHFormat = new SimpleDateFormat("MM/dd/yyyy HH"); + SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); + SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); + SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); + SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + SimpleDateFormat timestampFormat1 = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S"); + SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat YYYYFormat = new SimpleDateFormat("yyyy"); + java.util.Date date = null; + + int formatFlag = 0; + + final int YEARFLAG = 1; + final int MONTHFLAG = 2; + final int DAYFLAG = 3; + final int HOURFLAG = 4; + final int MINFLAG = 5; + final int SECFLAG = 6; + final int MILLISECFLAG = 7; + final int DAYOFTHEWEEKFLAG = 8; + final int FLAGDATE = 9; + /*int yearFlag = 1; + int monthFlag = 2; + int dayFlag = 3; + int hourFlag = 4; + int minFlag = 5; + int secFlag = 6; + int milliSecFlag = 7; + int dayoftheweekFlag = 8; + int flagDate = 10; + */ + + date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + if(date==null) { + date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYOFTHEWEEKFLAG; + } + if(date==null) { + date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + if(date==null) { + //MMDDYYYYHHFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = timestampFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + if(date==null) { + date = timestampHrFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = timestampDayFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = MONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = MMDDYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = timestampFormat1.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = YYYYFormat.parse(dateStr, new ParsePosition(0)); + /* Some random numbers should not satisfy this year format. */ + if(dateStr.length()>4) date = null; + if(date!=null) formatFlag = YEARFLAG; + } + if(date==null) + date = null; + return date; + } + + public int getFlagFromDateStr(String dateStr) { + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + SimpleDateFormat EEEMMDDYYYYFormat = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00 + SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); + SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); + SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat timestampHrFormat = new SimpleDateFormat("yyyy-MM-dd HH"); + SimpleDateFormat timestampDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + SimpleDateFormat MMDDYYYYHHFormat = new SimpleDateFormat("MM/dd/yyyy HH"); + SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); + SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); + SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); + SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); + SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); + SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + SimpleDateFormat timestampFormat1 = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S"); + SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat YYYYFormat = new SimpleDateFormat("yyyy"); + java.util.Date date = null; + + int formatFlag = 0; + + final int YEARFLAG = 1; + final int MONTHFLAG = 2; + final int DAYFLAG = 3; + final int HOURFLAG = 4; + final int MINFLAG = 5; + final int SECFLAG = 6; + final int MILLISECFLAG = 7; + final int DAYOFTHEWEEKFLAG = 8; + final int FLAGDATE = 9; + /*int yearFlag = 1; + int monthFlag = 2; + int dayFlag = 3; + int hourFlag = 4; + int minFlag = 5; + int secFlag = 6; + int milliSecFlag = 7; + int dayoftheweekFlag = 8; + int flagDate = 10; + */ + + date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + if(date==null) { + date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYOFTHEWEEKFLAG; + } + if(date==null) { + date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + if(date==null) { + //MMDDYYYYHHFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = timestampFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + if(date==null) { + date = timestampHrFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = HOURFLAG; + } + if(date==null) { + date = timestampDayFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = MONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + if(date==null) { + date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + if(date==null) { + date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MONTHFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = MMDDYYFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = DAYFLAG; + } + + if(date==null) { + date = timestampFormat1.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = SECFLAG; + } + + if(date==null) { + date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0)); + if(date!=null) formatFlag = MINFLAG; + } + + if(date==null) { + date = YYYYFormat.parse(dateStr, new ParsePosition(0)); + /* Some random numbers should not satisfy this year format. */ + if(dateStr.length()>4) date = null; + if(date!=null) formatFlag = YEARFLAG; + } + if(date==null) + date = null; + return formatFlag; + } + + public static String[] reverse(String[] arr) { + List list = Arrays.asList(arr); + Collections.reverse(list); + return (String[])list.toArray(); + } + + public int getNumberOfDecimalPlaces(double num) { + Double d = num; + String[] splitter = d.toString().split("\\."); + splitter[0].length(); // Before Decimal Count + splitter[1].length(); // After Decimal Count + return splitter[1].length(); + } + + public boolean getBooleanValue(String s) { + return getBooleanValue(s,null); + } + + public boolean getBooleanValue(String s, Boolean defaultValue) { + s = nvl(s); + if(s.length()<=0 && defaultValue!=null) return defaultValue.booleanValue(); + else if(s.length()<=0) return false; + else { + if(s.toUpperCase().startsWith("Y") || s.toLowerCase().equals("true")) + return true; + else + return false; + } + } + + + public String IntToLetter(int Int) { + if (Int<27){ + return Character.toString((char)(Int+96)); + } else { + if (Int%26==0) { + return IntToLetter((Int/26)-1)+IntToLetter((Int%26)+1); + } else { + return IntToLetter(Int/26)+IntToLetter(Int%26); + } + } + } + + + + + private void clearReportRuntimeBackup(HttpServletRequest request) { + //Session sess = Sessions.getCurrent(true)getCurrent(); + //HttpSession session = (HttpSession)sess.getNativeSession(); + HttpSession session = request.getSession(); + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + request.removeAttribute(AppConstants.DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.DRILLDOWN_INDEX); + request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + Enumeration enum1 = session.getAttributeNames(); + String attributeName = ""; + while(enum1.hasMoreElements()) { + attributeName = enum1.nextElement(); + if(attributeName.startsWith("parent_")) { + session.removeAttribute(attributeName); + } + } + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID); + session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); + session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP); + session.removeAttribute(AppConstants.SI_MAP); + session.removeAttribute(AppConstants.SI_MAP_OBJECT); + session.removeAttribute(AppConstants.SI_REPORT_DEFINITION); + session.removeAttribute(AppConstants.SI_REPORT_RUNTIME); + session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP); + session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE); + session.removeAttribute(AppConstants.RI_REPORT_DATA); + session.removeAttribute(AppConstants.RI_CHART_DATA); + session.removeAttribute(AppConstants.SI_FORMFIELD_INFO); + session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + + } // clearReportRuntimeBackup + + + public static synchronized java.util.HashMap getRequestParametersMap(ReportRuntime rr, HttpServletRequest request) + { + HashMap valuesMap = new HashMap(); + + ReportFormFields rff = rr.getReportFormFields(); + + int idx = 0; + FormField ff = null; + + Map fieldNameMap = new HashMap(); + int countOfFields = 0 ; + + + for(rff.resetNext(); rff.hasNext(); idx++) { + ff = rff.getNext(); + fieldNameMap.put(ff.getFieldName(), ff.getFieldDisplayName()); + countOfFields++; + } + + List formParameter = new ArrayList(); + String formField = ""; + for(int i = 0 ; i < rff.size(); i++) { + ff = ((FormField)rff.getFormField(i)); + formField = ff.getFieldName(); + boolean isMultiValue = false; + isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX) + || ff.getFieldType().equals(FormField.FFT_LIST_MULTI); + boolean isTextArea = (ff.getFieldType().equals(FormField.FFT_TEXTAREA) && rr.getReportDefType() + .equals(AppConstants.RD_SQL_BASED)); + + if(request.getParameterValues(formField) != null && isMultiValue ) { + String[] vals = request.getParameterValues(formField); + StringBuffer value = new StringBuffer(""); + if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) { + + if ( isMultiValue ) { + value.append("("); + } + for(int j = 0 ; j < vals.length; j++) { + if(isMultiValue) value.append("'"); + try { + if(vals[j] !=null && vals[j].length() > 0) { + vals[j] = Utils.oracleSafe(vals[j]); + value.append(java.net.URLDecoder.decode(vals[j], "UTF-8"));// + ","; + } + else + value.append(vals[j]); + } catch (UnsupportedEncodingException ex) {value.append(vals[j]);} + catch (IllegalArgumentException ex1){value.append(vals[j]);} + catch (Exception ex2){ + value.append(vals[j]); + } + + + if(isMultiValue) value.append("'"); + + if(j != vals.length -1) { + value.append(","); + } + } + if(vals.length > 0) { + value.append(")"); + } + } + + //value = value.substring(0 , value.length()); + + valuesMap.put(fieldNameMap.get(formField), value.toString()); + value = new StringBuffer(""); + } else if(request.getParameter(formField) != null) { + if(isTextArea) { + String value = ""; + value = request.getParameter(formField); + + value = Utils.oracleSafe(value); + value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; + value = Utils.replaceInString(value, "|", ","); + valuesMap.put(fieldNameMap.get(formField), value); + value = ""; + } else { + String value = ""; + if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) + value = request.getParameter(formField); + valuesMap.put(fieldNameMap.get(formField), Utils.oracleSafe(value)); + } + + } else { + valuesMap.put(fieldNameMap.get(formField), "" ); + } + + } + + return valuesMap; + + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartWebRuntime.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartWebRuntime.java new file mode 100644 index 00000000..b035187d --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ChartWebRuntime.java @@ -0,0 +1,423 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + + + + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.model.ReportHandler; +import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime; +import org.openecomp.portalsdk.analytics.system.AppUtils; +import org.openecomp.portalsdk.analytics.util.AppConstants; +import org.openecomp.portalsdk.analytics.view.ReportData; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + + +public class ChartWebRuntime implements Serializable { + + + // Not used - planned to use if Hibernate used as data access layer + private String runningDataQuery = ""; + private String runningCountQuery = ""; + //CONSTANTS FOR QUERY + public final String QRY_COUNT_REPORT = ""; + public final String QRY_DATA_REPORT = ""; + + // Not used planning to use when filter is used + private StringBuffer whereClause = new StringBuffer(""); + // request used to grab request parameters + private HttpServletRequest request; + + + public ReportRuntime reportRuntime; + public ReportData reportData; + + //Used to pass user information + private final Map params = new HashMap(); + + //from chart generator retrieves list of charts to render + public ArrayList chartList; + public ArrayList infoList; + + private String totalSql; + + + // + private String drilldown_index = "0"; + + public List getRolesCommaSeperated(HttpServletRequest request) { + HashMap roles = UserUtils.getRoles(request); + List roleList = null; + StringBuffer roleBuf = new StringBuffer(""); + int count = 0; + if( roles != null ) { + roleList = Arrays.asList(roles.keySet().toArray()); + } + + return roleList; + } + + + public String getUserId(HttpServletRequest request) { + return AppUtils.getUserID(request); + } + + public String generateChart(HttpServletRequest request) { + return generateChart(request, true); + } + + + public String generateChart(HttpServletRequest request, boolean showData) { + //wire variables + //processRecursive(this, this); + long currentTime = System.currentTimeMillis(); + HttpSession session = request.getSession(); + String action = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action")); + boolean genReportData = (!action.equals("chart.json") || action.equals("chart.data.json")); + + + + final Long user_id = new Long((long) UserUtils.getUserId(request)); + + + boolean adminUser = false; + try { + adminUser = AppUtils.isAdminUser(request) || AppUtils.isSuperUser(request); + } catch (RaptorException ex) { + ex.printStackTrace(); + } + List roleList = getRolesCommaSeperated(request); + //final Map params = new HashMap(); + params.put("user_id", user_id); + params.put("role_list", roleList); + //params.put("public_yn", "Y"); + + //String action = request.getParameter(AppConstants.RI_ACTION); + String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); + + ReportHandler rh = new ReportHandler(); + ReportRuntime rr = null; + try { + if(reportID !=null) + rr = rh.loadReportRuntime(request, reportID, true, 1); + if(rr.getReportType().equals(AppConstants.RT_HIVE)) { + String sql = rr.getReportSQL(); + rr.setWholeSQL(sql); + //if(genReportData) + //reportData = rr.loadHiveLinearReportData(rr.getWholeSQL(),user_id.toString(), 10000,request); + } else { + if(genReportData) + reportData = rr.loadReportData(0, user_id.toString(), 10000,request, false /*download*/); + } + } catch (RaptorException ex) { + ex.printStackTrace(); + } + setReportRuntime(rr); + setReportData( reportData); + + reportRuntime = getReportRuntime(); + reportData = getReportData(); + + + HashMap chartOptionsMap = new HashMap(); + + String rotateLabelsStr = ""; + rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle()); + if(rotateLabelsStr.toLowerCase().equals("standard")) { + rotateLabelsStr = "0"; + } else if (rotateLabelsStr.toLowerCase().equals("up45")) { + rotateLabelsStr = "45"; + } else if (rotateLabelsStr.toLowerCase().equals("down45")) { + rotateLabelsStr = "-45"; + } else if (rotateLabelsStr.toLowerCase().equals("up90")) { + rotateLabelsStr = "90"; + } else if (rotateLabelsStr.toLowerCase().equals("down90")) { + rotateLabelsStr = "-90"; + } else + rotateLabelsStr = "0"; + + String width = (AppUtils.getRequestNvlValue(request, "width").length()>0?AppUtils.getRequestNvlValue(request, "width"):(AppUtils.nvl(reportRuntime.getChartWidth()).length()>0?reportRuntime.getChartWidth():"700")); + String height = (AppUtils.getRequestNvlValue(request, "height").length()>0?AppUtils.getRequestNvlValue(request, "height"):(AppUtils.nvl(reportRuntime.getChartHeight()).length()>0?reportRuntime.getChartHeight():"300")); + String animationStr = (AppUtils.getRequestNvlValue(request, "animation").length()>0?AppUtils.getRequestNvlValue(request, "animation"):new Boolean(reportRuntime.isAnimateAnimatedChart()).toString()); + + String rotateLabels = (AppUtils.getRequestNvlValue(request, "rotateLabels").length()>0?AppUtils.getRequestNvlValue(request, "rotateLabels"):(rotateLabelsStr.length()>0?rotateLabelsStr:"0")); + String staggerLabelsStr = (AppUtils.getRequestNvlValue(request, "staggerLabels").length()>0?AppUtils.getRequestNvlValue(request, "staggerLabels"):"false"); + String showMaxMinStr = (AppUtils.getRequestNvlValue(request, "showMaxMin").length()>0?AppUtils.getRequestNvlValue(request, "showMaxMin"):"false"); + String showControlsStr = (AppUtils.getRequestNvlValue(request, "showControls").length()>0?AppUtils.getRequestNvlValue(request, "showControls"):new Boolean(reportRuntime.displayBarControls()).toString()); + String showLegendStr = (AppUtils.getRequestNvlValue(request, "showLegend").length()>0?AppUtils.getRequestNvlValue(request, "showLegend"):new Boolean(!new Boolean(reportRuntime.hideChartLegend())).toString()); + String topMarginStr = AppUtils.getRequestNvlValue(request, "topMargin"); + String topMargin = (AppUtils.nvl(topMarginStr).length()<=0)?(reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30"):topMarginStr; + String bottomMarginStr = AppUtils.getRequestNvlValue(request, "bottomMargin"); + String bottomMargin = (AppUtils.nvl(bottomMarginStr).length()<=0)?(reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50"):bottomMarginStr; + String leftMarginStr = AppUtils.getRequestNvlValue(request, "leftMargin"); + String leftMargin = (AppUtils.nvl(leftMarginStr).length()<=0)?(reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100"):leftMarginStr; + String rightMarginStr = AppUtils.getRequestNvlValue(request, "rightMargin"); + String rightMargin = (AppUtils.nvl(rightMarginStr).length()<=0)?(reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160"):rightMarginStr; + String showTitleStr = (AppUtils.getRequestNvlValue(request, "showTitle").length()>0?AppUtils.getRequestNvlValue(request, "showTitle"):new Boolean(reportRuntime.displayChartTitle()).toString()); + String subType = AppUtils.getRequestNvlValue(request, "subType").length()>0?AppUtils.getRequestNvlValue(request, "subType"):(AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():""); + String stackedStr = AppUtils.getRequestNvlValue(request, "stacked").length()>0?AppUtils.getRequestNvlValue(request, "stacked"):new Boolean(reportRuntime.isChartStacked()).toString(); + String horizontalBar = AppUtils.getRequestNvlValue(request, "horizontalBar").length()>0?AppUtils.getRequestNvlValue(request, "horizontalBar"):new Boolean(reportRuntime.isHorizontalOrientation()).toString(); + String barRealTimeAxis = AppUtils.getRequestNvlValue(request, "barRealTimeAxis"); + String barReduceXAxisLabels = AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels").length()>0?AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels"):new Boolean(reportRuntime.isLessXaxisTickers()).toString();; + String timeAxis = AppUtils.getRequestNvlValue(request, "timeAxis").length()>0?AppUtils.getRequestNvlValue(request, "timeAxis"):new Boolean(reportRuntime.isTimeAxis()).toString(); + String logScale = AppUtils.getRequestNvlValue(request, "logScale").length()>0?AppUtils.getRequestNvlValue(request, "logScale"):new Boolean(reportRuntime.isLogScale()).toString(); + String precision = AppUtils.getRequestNvlValue(request, "precision").length()>0?AppUtils.getRequestNvlValue(request, "precision"):"2"; + + /* boolean animation = AppUtils.getRequestFlag(request, "animation"); + boolean staggerLabels = AppUtils.getRequestFlag(request, "staggerLabels"); + boolean showMaxMin = (showMaxMinStr.length()<=0)?false:Boolean.parseBoolean(showMaxMinStr); + boolean showControls = (showControlsStr.length()<=0)?true:Boolean.parseBoolean(showControlsStr); + boolean showLegend = (showLegendStr.length()<=0)?true:Boolean.parseBoolean(showLegendStr); + boolean showTitle = (showTitleStr.length()<=0)?true:Boolean.parseBoolean(showTitleStr); + boolean stacked = (stackedStr.length()<=0)?true:Boolean.parseBoolean(stackedStr); + */ + // Add all options to Map + chartOptionsMap.put("width", width); + chartOptionsMap.put("height", height); + chartOptionsMap.put("animation", animationStr); + chartOptionsMap.put("rotateLabels", rotateLabels); + chartOptionsMap.put("staggerLabels", staggerLabelsStr); + chartOptionsMap.put("showMaxMin", showMaxMinStr); + chartOptionsMap.put("showControls", showControlsStr); + chartOptionsMap.put("showLegend", showLegendStr); + chartOptionsMap.put("topMargin", topMargin); + chartOptionsMap.put("bottomMargin", bottomMargin); + chartOptionsMap.put("leftMargin", leftMargin); + chartOptionsMap.put("rightMargin", rightMargin); + chartOptionsMap.put("showTitle", showTitleStr); + chartOptionsMap.put("subType", subType); + chartOptionsMap.put("stacked", stackedStr); + chartOptionsMap.put("horizontalBar", horizontalBar); + chartOptionsMap.put("timeAxis", timeAxis); + chartOptionsMap.put("barRealTimeAxis", barRealTimeAxis); + chartOptionsMap.put("barReduceXAxisLabels", barReduceXAxisLabels); + + chartOptionsMap.put("logScale", logScale); + chartOptionsMap.put("precision", precision); + + + + if(reportRuntime!=null) { + StringBuffer title = new StringBuffer(""); + title.append(reportRuntime.getReportName()); + } + + if(! (action.equals("chart.json") || action.equals("chart.data.json"))) { + + + //Chart + String chartType = reportRuntime.getChartType(); + return drawD3Charts(chartOptionsMap, request); + //drawD3Charts(); + } else /*if (action.equals("chart.json"))*/ { + String chartType = reportRuntime.getChartType(); + return returnChartJSON(chartOptionsMap, request, showData); + + + } /*else { + + return ("Internal Error Occurred."); + }*/ + + } + + + public String nvl(String s) { + return (s == null) ? "" : s; + } + + /** + * @return the reportRuntime + */ + public ReportRuntime getReportRuntime() { + return reportRuntime; + } + + /** + * @param reportRuntime the reportRuntime to set + */ + public void setReportRuntime(ReportRuntime reportRuntime) { + this.reportRuntime = reportRuntime; + } + + /** + * @return the reportData + */ + public ReportData getReportData() { + return reportData; + } + + /** + * @param reportData the reportData to set + */ + public void setReportData(ReportData reportData) { + this.reportData = reportData; + } + + public boolean isNull(String a) { + if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null")) + return true; + else + return false; + } + + + protected String nvl(String s, String sDefault) { + return nvl(s).equals("") ? sDefault : s; + } + + protected static String nvls(String s) { + return (s == null) ? "" : s; + } + + protected static String nvls(String s, String sDefault) { + return nvls(s).equals("") ? sDefault : s; + } + + protected boolean getFlagInBoolean(String s) { + return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true"); + } + + + /** + * @return the chartList + */ + public ArrayList getChartList() { + return chartList; + } + + /** + * @param chartList the chartList to set + */ + public void setChartList(ArrayList chartList) { + this.chartList = chartList; + } + + /** + * @return the infoList + */ + public ArrayList getInfoList() { + return infoList; + } + + /** + * @param infoList the infoList to set + */ + public void setInfoList(ArrayList infoList) { + this.infoList = infoList; + } + + + + private void clearReportRuntimeBackup(HttpSession session, HttpServletRequest request) { + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + request.removeAttribute(AppConstants.DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.DRILLDOWN_INDEX); + request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); + Enumeration enum1 = session.getAttributeNames(); + String attributeName = ""; + while(enum1.hasMoreElements()) { + attributeName = enum1.nextElement(); + if(attributeName.startsWith("parent_")) { + session.removeAttribute(attributeName); + } + } + session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); + session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID); + session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME); + session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP); + session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); + session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP); + session.removeAttribute(AppConstants.SI_MAP); + session.removeAttribute(AppConstants.SI_MAP_OBJECT); + session.removeAttribute(AppConstants.SI_REPORT_DEFINITION); + session.removeAttribute(AppConstants.SI_REPORT_RUNTIME); + session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP); + session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE); + session.removeAttribute(AppConstants.RI_REPORT_DATA); + session.removeAttribute(AppConstants.RI_CHART_DATA); + session.removeAttribute(AppConstants.SI_FORMFIELD_INFO); + session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); + } // clearReportRuntimeBackup + + + public String getTotalSql() { + return totalSql; + } + + public void setTotalSql(String totalSql) { + this.totalSql = totalSql; + } + + + + /* public void drawD3Charts(HashMap chartOptionsMap) { + drawD3Charts(chartOptionsMap); + + } + */ + + public String drawD3Charts(HashMap chartOptionsMap, HttpServletRequest request) { + + ChartD3Helper chartHelper = new ChartD3Helper(reportRuntime); + chartHelper.setChartType(reportRuntime.getChartType()); + try { + return chartHelper.createVisualization(reportRuntime, chartOptionsMap, request); + } catch(RaptorException ex) { + ex.printStackTrace(); + } + return ""; + + } + + public String returnChartJSON(HashMap chartOptionsMap, HttpServletRequest request, boolean showData) { + + ChartJSONHelper chartJSONHelper = new ChartJSONHelper(reportRuntime); + chartJSONHelper.setChartType(reportRuntime.getChartType()); + try { + return chartJSONHelper.generateJSON(reportRuntime, chartOptionsMap, request, showData); + } catch(RaptorException ex) { + ex.printStackTrace(); + } + return ""; + + } + + } + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CommonChartOptions.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CommonChartOptions.java new file mode 100644 index 00000000..e3e9fc67 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/CommonChartOptions.java @@ -0,0 +1,81 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +public class CommonChartOptions { + + private String legendPosition = "top"; + private String legendLabelAngle = "up45"; + private boolean hideLegend = false; + private boolean animateAnimatedChart = true; + private int topMargin = 30; + private int bottomMargin = 50; + private int leftMargin = 100; + private int rightMargin = 60; + + public String getLegendPosition() { + return legendPosition; + } + public void setLegendPosition(String legendPosition) { + this.legendPosition = legendPosition; + } + public String getLegendLabelAngle() { + return legendLabelAngle; + } + public void setLegendLabelAngle(String legendLabelAngle) { + this.legendLabelAngle = legendLabelAngle; + } + public boolean isHideLegend() { + return hideLegend; + } + public void setHideLegend(boolean hideLegend) { + this.hideLegend = hideLegend; + } + public boolean isAnimateAnimatedChart() { + return animateAnimatedChart; + } + public void setAnimateAnimatedChart(boolean animateAnimatedChart) { + this.animateAnimatedChart = animateAnimatedChart; + } + public int getTopMargin() { + return topMargin; + } + public void setTopMargin(int topMargin) { + this.topMargin = topMargin; + } + public int getBottomMargin() { + return bottomMargin; + } + public void setBottomMargin(int bottomMargin) { + this.bottomMargin = bottomMargin; + } + public int getLeftMargin() { + return leftMargin; + } + public void setLeftMargin(int leftMargin) { + this.leftMargin = leftMargin; + } + public int getRightMargin() { + return rightMargin; + } + public void setRightMargin(int rightMargin) { + this.rightMargin = rightMargin; + } +} \ No newline at end of file diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ErrorJSONRuntime.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ErrorJSONRuntime.java new file mode 100644 index 00000000..04068ef2 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/ErrorJSONRuntime.java @@ -0,0 +1,58 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; + +import org.json.JSONObject; +import org.openecomp.portalsdk.analytics.model.base.IdNameValue; +import org.openecomp.portalsdk.analytics.view.ColumnHeader; +import org.openecomp.portalsdk.analytics.view.DataValue; +import org.openecomp.portalsdk.analytics.xmlobj.ColFilterList; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnList; +import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType; + +public class ErrorJSONRuntime { + + private String errormessage; + private String stacktrace; + + public String getErrormessage() { + return errormessage; + } + public void setErrormessage(String errormessage) { + this.errormessage = errormessage; + } + public String getStacktrace() { + return stacktrace; + } + public void setStacktrace(String stacktrace) { + this.stacktrace = stacktrace; + } + + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FlexTimeSeriesChartOptions.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FlexTimeSeriesChartOptions.java new file mode 100644 index 00000000..3b3060bb --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FlexTimeSeriesChartOptions.java @@ -0,0 +1,38 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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.openecomp.portalsdk.analytics.model.runtime; + +public class FlexTimeSeriesChartOptions { + private int zoomIn = 25; + private String timeAxisType = ""; + public int getZoomIn() { + return zoomIn; + } + public void setZoomIn(int zoomIn) { + this.zoomIn = zoomIn; + } + public String getTimeAxisType() { + return timeAxisType; + } + public void setTimeAxisType(String timeAxisType) { + this.timeAxisType = timeAxisType; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FormField.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FormField.java new file mode 100644 index 00000000..6d9730a5 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/model/runtime/FormField.java @@ -0,0 +1,2103 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ================================================================================ + */ +/* =========================================================================================== + * This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting) + * Raptor : This tool is used to generate different kinds of reports with lot of utilities + * =========================================================================================== + * + * ------------------------------------------------------------------------------------------- + * FormField.java - This class is used to generate all types of form field. + * ------------------------------------------------------------------------------------------- + * + * Created By : Stan Pishamanov + * Modified & Maintained By : Sundar Ramalingam + * + * Changes + * ------- + * 18-Aug-2009 : Version 8.5 (Sundar); Populating predefined formfields bug has been resolved. + * 13-Aug-2009 : Version 8.5 (RS); Form field chaining is supported even for hidden variables. + * 13-Aug-2009 : Version 8.5 (RS); Nothing changed just comment. + * 10-Aug-2009 : Version 9.0 (RS); required logic is added for Multiple Dropdown. + * 06-Aug-2009 : Version 9.0 (RS); B getAjaxHtml is added for converting form field chain from Iframe to AJAX. + * 08-Jun-2009 : Version 8.3 (RS); Hidden formfields now is displayed even when the sql is not provided. + * + */ +package org.openecomp.portalsdk.analytics.model.runtime; + +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction; + +import org.openecomp.portalsdk.analytics.error.RaptorException; +import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException; +import org.openecomp.portalsdk.analytics.error.UserDefinedException; +import org.openecomp.portalsdk.analytics.model.base.*; +import org.openecomp.portalsdk.analytics.system.*; +import org.openecomp.portalsdk.analytics.util.*; +import org.openecomp.portalsdk.analytics.xmlobj.*; + +public class FormField extends org.openecomp.portalsdk.analytics.RaptorObject implements Serializable { + private static final String HTML_FORM = "formd"; + + private String fieldName = null; + + private String fieldDisplayName = null; + + private String fieldType = FFT_TEXT_W_POPUP; + + private String validationType = VT_NONE; + + private boolean required = false; + + public boolean hasPredefinedList = false; + + private String defaultValue = null; + + private Calendar rangeStartDate = null; + + private Calendar rangeEndDate = null; + + private String rangeStartDateSQL = null; + + private String rangeEndDateSQL = null; + + private String fieldDefaultSQL = null; + + private String multiSelectListSize = null; + + private String helpText = null; + + private IdNameList lookupList = null; + + private String dbInfo = null; + + private String userId = null; + + private boolean visible = true; + + private String dependsOn = null; + + private boolean triggerOtherFormFields = false; + + private boolean triggerThisFormfield = false; + + // Form field types + public static final String FFT_TEXT_W_POPUP = "TEXT_WITH_POPUP"; + + public static final String FFT_TEXT = "TEXT"; + + public static final String FFT_TEXTAREA = "TEXTAREA"; + + public static final String FFT_COMBO_BOX = "COMBO_BOX"; + + public static final String FFT_LIST_BOX = "LIST_BOX"; + + public static final String FFT_RADIO_BTN = "RADIO_BTN"; + + public static final String FFT_CHECK_BOX = "CHECK_BOX"; + + public static final String FFT_LIST_MULTI = "LIST_MULTI_SELECT"; + + public static final String FFT_HIDDEN = "HIDDEN"; + + public static final String FFT_BLANK = "BLANK"; + + // Validation types + public static final String VT_NONE = "NONE"; + + public static final String VT_DATE = "DATE"; + + public static final String VT_TIMESTAMP_HR = "TIMESTAMP_HR"; + + public static final String VT_TIMESTAMP_MIN = "TIMESTAMP_MIN"; + + public static final String VT_TIMESTAMP_SEC = "TIMESTAMP_SEC"; + + public static final String VT_INT = "INTEGER"; + + public static final String VT_INT_POSITIVE = "POSITIVE_INTEGER"; + + public static final String VT_INT_NON_NEGATIVE = "NON_NEGATIVE_INTEGER"; + + public static final String VT_FLOAT = "FLOAT"; + + public static final String VT_FLOAT_POSITIVE = "POSITIVE_FLOAT"; + + public static final String VT_FLOAT_NON_NEGATIVE = "NON_NEGATIVE_FLOAT"; + + private FormField(String fieldName, String fieldDisplayName, String fieldType, + String validationType, boolean required, String defaultValue, String helpText, boolean visible, String dependsOn, Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize ) { + //super(); + this (fieldName,fieldDisplayName,fieldType,validationType,required,defaultValue,helpText, dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); + setVisible(visible); + } // FormField + + private FormField(String fieldName, String fieldDisplayName, String fieldType, + String validationType, boolean required, String defaultValue, String helpText, String dependsOn, Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize ) { + super(); + setFieldName(fieldName); + setFieldDisplayName(fieldDisplayName); + setFieldType(nvl(fieldType, FFT_TEXT)); + setValidationType(validationType); + setRequired(required); + setDefaultValue(defaultValue); + setHelpText(helpText); + setDependsOn(dependsOn); + setRangeStartDate(rangeStartDate); + setRangeEndDate(rangeEndDate); + setRangeStartDateSQL(rangeStartDateSQL); + setRangeEndDateSQL(rangeEndDateSQL); + setMultiSelectListSize(multiSelectListSize); + } + public FormField(String fieldName, String fieldDisplayName, String fieldType, + String validationType, boolean required, String defaultValue, String helpText, + List predefinedValues, boolean visible, String dependsOn, Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize) { + this(fieldName, fieldDisplayName, fieldType, validationType, required, defaultValue, + helpText,visible, dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); + if (predefinedValues != null) + setPredefinedListLookup(predefinedValues); + } // FormField + + public FormField(String fieldName, String fieldDisplayName, String fieldType, + String validationType, boolean required, String defaultValue, String helpText, + String lookupSql, boolean visible, String dependsOn, Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize ) { + this(fieldName, fieldDisplayName, fieldType, validationType, required, defaultValue, + helpText,visible, dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); + if (defaultValue!=null && defaultValue.length()>10 && defaultValue.substring(0,10).trim().toLowerCase().startsWith("select")) { + setFieldDefaultSQL(defaultValue); + setDefaultValue(""); + } + setLookupList(new IdNameSql(lookupSql,defaultValue)); + } // FormField + + public FormField(String fieldName, String fieldDisplayName, String fieldType, + String validationType, boolean required, String defaultValue, String helpText, + String dbTableName, String dbIdField, String dbNameField, String dbSortByField, boolean visible, String dependsOn, Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize) { + this(fieldName, fieldDisplayName, fieldType, validationType, required, defaultValue, + helpText,dbTableName,dbIdField,dbNameField,dbSortByField, dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); + setVisible(visible); + } + + public FormField(String fieldName, String fieldDisplayName, String fieldType, + String validationType, boolean required, String defaultValue, String helpText, + String dbTableName, String dbIdField, String dbNameField, String dbSortByField, String dependsOn, + Calendar rangeStartDate, Calendar rangeEndDate, + String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize ) { + this(fieldName, fieldDisplayName, fieldType, validationType, required, defaultValue, + helpText,dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); + //if(dependsOn !=null){ this.dependsOn = dependsOn; }else { this.dependsOn = "" + if (defaultValue!=null && defaultValue.length()>10 && defaultValue.substring(0,10).trim().toLowerCase().startsWith("select")) { + setFieldDefaultSQL(defaultValue); + setDefaultValue(""); + if(fieldType.equals(FFT_TEXT)) + setLookupList(new IdNameLookup(dbTableName, dbIdField, dbNameField, dbSortByField,defaultValue,true)); + else + setLookupList(new IdNameLookup(dbTableName, dbIdField, dbNameField, dbSortByField,defaultValue,false)); + } + else { + if(fieldType.equals(FFT_TEXT)) + setLookupList(new IdNameLookup(dbTableName, dbIdField, dbNameField, dbSortByField, true)); + else + setLookupList(new IdNameLookup(dbTableName, dbIdField, dbNameField, dbSortByField, false)); + } + + this.setRangeStartDate(rangeStartDate); + this.setRangeEndDate(rangeEndDate); + this.setRangeStartDateSQL(rangeStartDateSQL); + this.setRangeEndDateSQL(rangeEndDateSQL); + + } // FormField + + + private void setPredefinedListLookup(List predefinedValues) { + IdNameList lookup = new IdNameList(); + for (Iterator iter = predefinedValues.iterator(); iter.hasNext();) { + String value = (String) iter.next(); + lookup.addValue(value, value); + } // for + setHasPredefinedList(true); + setLookupList(lookup); + } // setPredefinedListLookup + + public String getFieldName() { + return fieldName; + } + + public String getFieldDisplayName() { + return fieldDisplayName; + } + + public String getFieldType() { + return fieldType; + } + + public String getValidationType() { + return validationType; + } + + public boolean isRequired() { + return required; + } + + public String getDefaultValue() { + return defaultValue; + } + + public String getHelpText() { + return helpText; + } + + public IdNameList getLookupList() { + return lookupList; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public void setFieldDisplayName(String fieldDisplayName) { + this.fieldDisplayName = fieldDisplayName; + } + + public void setFieldType(String fieldType) { + this.fieldType = fieldType; + } + + public void setValidationType(String validationType) { + this.validationType = nvl(validationType, VT_NONE); + } + + public void setRequired(boolean required) { + this.required = required; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public void setHelpText(String helpText) { + this.helpText = helpText; + } + + public void setLookupList(IdNameList lookupList) { + this.lookupList = lookupList; + } + + public void setDefaultList(IdNameList lookupList) { + this.lookupList = lookupList; + } + + public String getBaseSQL() { + return (lookupList == null) ? null : lookupList.getBaseSQL(); + } // getBaseSQL + + public String getBaseWholeSQL() { + return (lookupList == null) ? null : lookupList.getBaseWholeSQL(); + } // getBaseWholeSQL + + public String getBaseWholeReadonlySQL() { + return (lookupList == null) ? null : lookupList.getBaseWholeReadonlySQL(); + } // getBaseWholeReadonlySQL + + public String getBaseSQLForPDFExcel() { + return (lookupList == null) ? null : lookupList.getBaseSQLForPDFExcel(getFieldType().equals(FFT_LIST_MULTI)||getFieldType().equals(FFT_CHECK_BOX)?true:false); + } // getBaseSQLForPDFExcel + + public String getDisplayNameHtml() { + if (nvl(helpText).length() > 0) + return "" + fieldDisplayName + ""; + else + return fieldDisplayName; + } // getDisplayNameHtml + + /*public String getHtml() throws RaptorRuntimeException { + return getHtml("" , null, null, false); + } // getHtml*/ + + public String getHtml(String fieldValue, HashMap formValues, ReportRuntime rr)throws RaptorRuntimeException { + return getHtml(fieldValue,formValues, rr, false); + } + + public String getHelpLink(String fieldName) { + //return "\"\""; + return ((getHelpText()!=null && getHelpText().length()>0)? "tooltipText=\""+ getHelpText()+"\">": ">"); + //return ((getHelpText()!=null && getHelpText().length()>0)? "": ""); + } + + + public String getCallableAfterChainingJavascript(String fieldName, ReportRuntime rr) { + JavascriptItemType javascriptItemType = null; + StringBuffer callJavascriptText = new StringBuffer(""); + if(rr.getJavascriptList()!=null) { + for (Iterator iter = rr.getJavascriptList().getJavascriptItem().iterator(); iter.hasNext();) { + javascriptItemType = (JavascriptItemType)iter.next(); + if(javascriptItemType.getFieldId().equals(fieldName)) { + if(nvl(javascriptItemType.getCallText()).toLowerCase().startsWith("afterchaining")) + callJavascriptText.append(" "+javascriptItemType.getCallText()); + } + } + } + return callJavascriptText.toString()+" "; + } + public String getCallableJavascript(String fieldName, ReportRuntime rr) { + JavascriptItemType javascriptItemType = null; + StringBuffer callJavascriptText = new StringBuffer(""); + if(rr.getJavascriptList()!=null) { + for (Iterator iter = rr.getJavascriptList().getJavascriptItem().iterator(); iter.hasNext();) { + javascriptItemType = (JavascriptItemType)iter.next(); + if(javascriptItemType.getFieldId().equals(fieldName)) { + if(!nvl(javascriptItemType.getCallText()).toLowerCase().startsWith("afterchaining")) + callJavascriptText.append(" "+javascriptItemType.getCallText()); + } + } + } + return callJavascriptText.toString()+" "; + } + + public String getCallableOnChangeJavascript(String fieldName, ReportRuntime rr) { + String callText = getCallableJavascript(fieldName, rr); + if(callText != null && callText.trim().toLowerCase().indexOf("onchange")>=0) { + Pattern re1 = Pattern.compile("\\=(.*?)\\)"); + Matcher matcher = re1.matcher(callText); + while (matcher.find()) { + callText = matcher.group(); + if(callText!=null && callText.startsWith("=\"")) { + callText = callText.substring(2); + } else if (callText!=null) + callText = callText.substring(1); + } + callText = callText.replaceAll("this", "documentForm."+fieldName); + } else callText = null; + return callText; + } + + public String getAjaxHtml(String fieldValue, HashMap formValues, ReportRuntime rr, boolean inSchedule) throws RaptorRuntimeException { + fieldValue = nvl(fieldValue, defaultValue); + String readOnly = "ff_readonly"; + try { + if(fieldValue !=null && fieldValue.length() > 0) + fieldValue = java.net.URLDecoder.decode(fieldValue, "UTF-8"); + } catch (UnsupportedEncodingException ex) {} + catch (IllegalArgumentException ex1){} + catch (Exception ex2){} + if (fieldType.equals(FFT_COMBO_BOX)) { + StringBuffer sb = new StringBuffer(); + //System.out.println("COMBO BOX " + fieldName); + String oldSQL = ""; + if (!required) + sb.append("obj.options[obj.options.length] = new Option('-->select value<--','');"); + + IdNameList lookup = getLookupList(); + try { + if(!hasPredefinedList) { + //if(dependsOn != null && dependsOn != "") { + //if(dependsOn != null && dependsOn != "" ) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = ""; + SQL = lu.getSql(); + /*if(nvl(fieldValue,"").length()<=0) + SQL = lu.getSql(); + else + SQL = lu.getBaseSQLForPDFExcel(false); + */ + //System.out.println("FORMFIELD 6666667 First" + ((IdNameSql)lookup).getSql()); + oldSQL = lu.getSql(); + //SQL = Utils.replaceInString(SQL, "[VALUE]", fieldValue); + if(formValues != null) { + Set set = formValues.entrySet(); + String value = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + value = (String) entry.getValue(); + if(inSchedule) { + try { + value = java.net.URLDecoder.decode(Utils.oracleSafe(value), "UTF-8"); + } catch (UnsupportedEncodingException ex) { + + } + } + if (value!=null && (value.length() <=0 || value.equals("NULL"))) { + value = "NULL"; + SQL = Utils.replaceInString(SQL, "'["+entry.getKey()+"]'", value); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); + } else { + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); + } + } + lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); + } + //} + lookupList = lookup; + + //} + try { + lookup.loadUserData(0, "", getDbInfo(), getUserId()); + } catch (Exception e ){ e.printStackTrace(); //throw new RaptorRuntimeException(e); + } + } + lookup.trimToSize(); + + String selectedValue = ""; + int count = 0; + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + if(value != null && value.getId() != null && value.getName() != null ) { + /*if (count == 0 && required) { + selectedValue = value.getId(); + count++; + } else if (nvl(fieldValue).length()>0){ + if (fieldValue != null && fieldValue.equals(value.getId())){ + selectedValue = value.getId(); + } + count++; + } else { + count++; + } */ + if (count == 0) { + if(required){ + selectedValue = value.getId(); + } + count++; + } + sb.append("obj.options[obj.options.length] = new Option('" + Utils.singleQuoteEncode(value.getName())+"','"+Utils.singleQuoteEncode(value.getId())+"');"); + if ((fieldValue != null && fieldValue.equals(value.getId()))){ + sb.append("obj.options[obj.options.length-1].selected=true;"); + selectedValue = value.getId(); + } + if(value.isReadOnly()) + sb.append("obj.disabled=true;"); + else + sb.append("obj.disabled=false;"); + + } + } // for + if (formValues.containsKey(fieldDisplayName)){ + formValues.remove(fieldDisplayName); + } + formValues.put(fieldDisplayName, selectedValue); + } catch (Exception e) { + //throw new RaptorRuntimeException(e); + } + if(!hasPredefinedList) { + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + } + //System.out.println("FORMFIELD 6666667 " + ((IdNameSql)lookup).getSql()); + if( isVisible()) + return sb.toString(); + else return ""; + } else if (fieldType.equals(FFT_LIST_MULTI)) { + StringBuffer sb = new StringBuffer(); + String oldSQL = ""; + + fieldValue = '|' + fieldValue + '|'; + IdNameList lookup = getLookupList(); + try { + if(!hasPredefinedList) { + //if(dependsOn != null && dependsOn != "") { + //if(dependsOn != null && dependsOn != "" ) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = ""; + SQL = lu.getSql(); + /*if(nvl(fieldValue,"").length()<=0) + SQL = lu.getSql(); + else + SQL = lu.getBaseSQLForPDFExcel(false); + SQL = Utils.replaceInString(SQL, "[VALUE]", fieldValue); + */ + oldSQL = lu.getSql(); + if(formValues != null) { + Set set = formValues.entrySet(); + String value = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + value = (String) entry.getValue(); + if(inSchedule) { //('1347') + try { + value = java.net.URLDecoder.decode(value, "UTF-8"); + } catch (UnsupportedEncodingException ex) { + + } + } + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); + } + lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); + } + //} + lookupList = lookup; + //} + + lookup.loadUserData(0, "", getDbInfo(),getUserId()); + } + + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + sb.append("obj.options[obj.options.length] = new Option('" + Utils.singleQuoteEncode(value.getName()) +"','"+Utils.singleQuoteEncode(value.getId())+"');"); + if (fieldValue.indexOf('|' + value.getId() + '|') >= 0) + sb.append("obj.options[obj.options.length-1].selected=true;"); + if(value.isReadOnly()) + sb.append("obj.disabled=true;"); + else + sb.append("obj.disabled=false;"); + + } // for + + // lookup.clearData(); + } catch (Exception e) { + //throw new RaptorRuntimeException(e); + } + if(!hasPredefinedList) { + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + } + if(isVisible()) + return sb.toString(); + else + return ""; + } else if (fieldType.equals(FFT_TEXT_W_POPUP)) { + //System.out.println("TEXT POPUP " + fieldName); + String oldSQL = ""; + IdNameValue idNamevalue = null; + String fieldDefValue=""; + String fieldDefDisplay=""; + try { + IdNameList lookup = getLookupList(); + if(dependsOn != null && dependsOn != "" ) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = getBaseWholeSQL(); + if(SQL.toLowerCase().indexOf(readOnly) != -1) { + SQL = getBaseWholeReadonlySQL(); + } + oldSQL = lu.getSql(); + if(formValues != null) { + Set set = formValues.entrySet(); + String value = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + value = (String) entry.getValue(); + if(inSchedule) { + try { + value = java.net.URLDecoder.decode(Utils.oracleSafe(value), "UTF-8"); + } catch (UnsupportedEncodingException ex) { + + } + } + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); +// if(SQL.indexOf("'"+"["+entry.getKey()+"]"+"'")!=-1) { + if(SQL.indexOf("'"+"["+entry.getKey()+"]"+"'")!=-1 || SQL.indexOf("'"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"'")!=-1 + || SQL.indexOf("'%"+"["+entry.getKey()+"]"+"%'")!=-1 || SQL.indexOf("'%"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"%'")!=-1 + || SQL.indexOf("'_"+"["+entry.getKey()+"]"+"_'")!=-1 || SQL.indexOf("'_"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"_'")!=-1 + || SQL.indexOf("'%_"+"["+entry.getKey()+"]"+"_%'")!=-1 || SQL.indexOf("'%_"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"_%'")!=-1) { + + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", nvl( + value, "NULL")); + } else { + // Added to prevent SQL Injection + if(SQL.indexOf("["+entry.getKey()+"]")!=-1) { + try { + double vD = Double.parseDouble(value); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", nvl( + value, "NULL")); + } catch (NumberFormatException ex) { + throw new UserDefinedException("Expected number, Given String for the form field \"" + "["+entry.getKey()+"]"+"\""); + } + } + } + } + if(getFieldDefaultSQL()!=null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.trim().length()<=0)) + lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); + else + lookup = new IdNameSql(-1,SQL,null); + } + } + //lookupList = lookup; + + if(getFieldDefaultSQL()!=null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.trim().length()<=0)) { + lookup.loadUserData(0, "", getDbInfo(), getUserId()); + for (lookup.resetNext(); lookup.hasNext();) { + idNamevalue = lookup.getNext(); + break; + + } + fieldDefValue = nvl(idNamevalue.getId()); + fieldDefDisplay = nvl(idNamevalue.getName()); + } else { + try { + // -2 indicates to run the whole sql for matching value + lookup.loadUserData(-2, "", getDbInfo(), getUserId()); + lookup.trimToSize(); + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + if(value != null && value.getId() != null && value.getName() != null ) { + fieldDefValue = nvl(value.getId()); + if (fieldValue != null && fieldValue.equals(value.getId())) { + fieldDefDisplay = nvl(value.getName()); + break; + } + else { + fieldDefValue = ""; + fieldDefDisplay = ""; + } + } + } + if (fieldDefDisplay == null || fieldDefDisplay.length()<=0) { + fieldDefDisplay = nvl(fieldDefValue); + } + + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + + } catch (Exception e) { + //throw new RaptorRuntimeException(e); + } + + + //----- END ---// + + + if(getFieldDefaultSQL()!=null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.length()<=0)) { + fieldDefValue = nvl((idNamevalue!=null)?idNamevalue.getId():""); + fieldDefDisplay = nvl((idNamevalue!=null)?idNamevalue.getName():""); + } else { + if(fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.length()<=0) fieldValue=""; + fieldDefValue = nvl(fieldDefValue); + fieldDefDisplay = nvl(fieldDefDisplay); + } + + } + }catch(Exception e) { //throw new RaptorRuntimeException(e); + } + if(isVisible()) { + /* return "\n" + "0 && (dependsOn == null || dependsOn.length()<=0)) { + sb.append((fieldValue!=null)?"obj.value=\""+nvl(fieldValue)+"\";":""); + } else if (lookup != null) { + lookup.loadUserData(0, "", getDbInfo(), getUserId()); + int iCnt = 0; + for (lookup.resetNext(); lookup.hasNext(); iCnt++) { + IdNameValue value = lookup.getNext(); + //System.out.println("HIDDEN " + value.getId() + " " + value.getName()); + sb.append((value!=null)?"obj.value=\""+nvl(value.getId())+"\";":""); + if(value.isReadOnly()) + sb.append("obj.disabled=true;"); + else + sb.append("obj.disabled=false;"); + break; + } // for + if(lookup.size()<=0) { + sb.append("obj.value=\"\""); + + } + } else { + sb.append((fieldValue!=null)?"obj.value=\""+Utils.singleQuoteEncode(nvl(fieldValue))+"\";":""); + } + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + // lookup.clearData(); + } catch (Exception e) { + //throw new RaptorRuntimeException(e); + } + //if(isVisible()) + return sb.toString() ; + } else if (fieldType.equals(FFT_LIST_BOX)) { + StringBuffer sb = new StringBuffer(); + //System.out.println("COMBO BOX " + fieldName); + String oldSQL = ""; + if (!required) + sb.append("obj.options[obj.options.length] = new Option('-->select value<--','');"); + + IdNameList lookup = getLookupList(); + try { + if(!hasPredefinedList) { + //if(dependsOn != null && dependsOn != "") { + //if(dependsOn != null && dependsOn != "" ) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = ""; + SQL = lu.getSql(); + /*if(nvl(fieldValue,"").length()<=0) + SQL = lu.getSql(); + else + SQL = lu.getBaseSQLForPDFExcel(false); + */ + //System.out.println("FORMFIELD 6666667 First" + ((IdNameSql)lookup).getSql()); + oldSQL = lu.getSql(); + //SQL = Utils.replaceInString(SQL, "[VALUE]", fieldValue); + if(formValues != null) { + Set set = formValues.entrySet(); + String value = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + value = (String) entry.getValue(); + if(inSchedule) { + try { + value = java.net.URLDecoder.decode(Utils.oracleSafe(value), "UTF-8"); + } catch (UnsupportedEncodingException ex) { + + } + } + if (value!=null && (value.length() <=0 || value.equals("NULL"))) { + value = "NULL"; + SQL = Utils.replaceInString(SQL, "'["+entry.getKey()+"]'", value); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); + } else { + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); + } + } + lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); + } + //} + lookupList = lookup; + + //} + try { + lookup.loadUserData(0, "", getDbInfo(), getUserId()); + } catch (Exception e ){ e.printStackTrace(); //throw new RaptorRuntimeException(e); + } + } + lookup.trimToSize(); + + String selectedValue = ""; + int count = 0; + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + if(value != null && value.getId() != null && value.getName() != null ) { + /*if (count == 0 && required) { + selectedValue = value.getId(); + count++; + } else if (nvl(fieldValue).length()>0){ + if (fieldValue != null && fieldValue.equals(value.getId())){ + selectedValue = value.getId(); + } + count++; + } else { + count++; + } */ + if (count == 0) { + if(required){ + selectedValue = value.getId(); + } + count++; + } + sb.append("obj.options[obj.options.length] = new Option('" + Utils.singleQuoteEncode(value.getName())+"','"+Utils.singleQuoteEncode(value.getId())+"');"); + if ((fieldValue != null && fieldValue.equals(value.getId()))){ + sb.append("obj.options[obj.options.length-1].selected=true;"); + selectedValue = value.getId(); + } + if(value.isReadOnly()) + sb.append("obj.disabled=true;"); + else + sb.append("obj.disabled=false;"); + + } + } // for + if (formValues.containsKey(fieldDisplayName)){ + formValues.remove(fieldDisplayName); + } + formValues.put(fieldDisplayName, selectedValue); + } catch (Exception e) { + //throw new RaptorRuntimeException(e); + } + if(!hasPredefinedList) { + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + } + //System.out.println("FORMFIELD 6666667 " + ((IdNameSql)lookup).getSql()); + if( isVisible()) + return sb.toString(); + else return ""; + } + + return ""; + } + + public String getHtml(String fieldValue, HashMap formValues, ReportRuntime rr, boolean inSchedule) throws RaptorRuntimeException { + fieldValue = nvl(fieldValue, defaultValue); + int MILLIS_IN_DAY = 1000 * 60 * 60 * 24; + String readOnlyInSql = "ff_readonly"; + boolean readOnly = false; + try { + if(fieldValue !=null && fieldValue.length() > 0) + fieldValue = java.net.URLDecoder.decode(fieldValue, "UTF-8"); + } catch (UnsupportedEncodingException ex) {} + catch (IllegalArgumentException ex1){} + catch (Exception ex2){} + //System.out.println(fieldName + " " + fieldType + " " + fieldValue); + if (fieldType.equals(FFT_TEXT_W_POPUP)) { + //System.out.println("TEXT POPUP " + fieldName); + String oldSQL = ""; + IdNameValue idNamevalue = null; + String fieldDefValue=""; + String fieldDefDisplay=""; + IdNameList lookup = null; + try { + lookup = getLookupList(); + if(!hasPredefinedList) { + if(dependsOn != null && dependsOn != "" ) { + IdNameSql lu = (IdNameSql) lookup; + String SQL = getBaseWholeSQL(); + if(SQL.toLowerCase().indexOf(readOnlyInSql) != -1) { + SQL = getBaseWholeReadonlySQL(); + } + oldSQL = lu.getSql(); + if(formValues != null) { + Set set = formValues.entrySet(); + String value = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + value = (String) entry.getValue(); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value); +// if(SQL.indexOf("'"+"["+entry.getKey()+"]"+"'")!=-1) { + if(SQL.indexOf("'"+"["+entry.getKey()+"]"+"'")!=-1 || SQL.indexOf("'"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"'")!=-1 + || SQL.indexOf("'%"+"["+entry.getKey()+"]"+"%'")!=-1 || SQL.indexOf("'%"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"%'")!=-1 + || SQL.indexOf("'_"+"["+entry.getKey()+"]"+"_'")!=-1 || SQL.indexOf("'_"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"_'")!=-1 + || SQL.indexOf("'%_"+"["+entry.getKey()+"]"+"_%'")!=-1 || SQL.indexOf("'%_"+"["+entry.getKey())!=-1 || SQL.indexOf(entry.getKey()+"]"+"_%'")!=-1) { + + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", nvl( + value, "NULL")); + } else { + // Added to prevent SQL Injection + if(SQL.indexOf("["+entry.getKey()+"]")!=-1) { + try { + double vD = Double.parseDouble(value); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", nvl( + value, "NULL")); + } catch (NumberFormatException ex) { + throw new UserDefinedException("Expected number, Given String for the form field \"" + "["+entry.getKey()+"]"+"\""); + } + } + } + } + if(getFieldDefaultSQL()!=null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.trim().length()<=0)) + lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); + else + lookup = new IdNameSql(-1,SQL,null); + } + } + //lookupList = lookup; + + if(getFieldDefaultSQL()!=null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.trim().length()<=0)) { + lookup.loadUserData(0, "", getDbInfo(), getUserId()); + for (lookup.resetNext(); lookup.hasNext();) { + idNamevalue = lookup.getNext(); + break; + + } + fieldDefValue = nvl(idNamevalue.getId()); + fieldDefDisplay = nvl(idNamevalue.getName()); + } else { + try { + // -2 indicates to run the whole sql for matching value + lookup.loadUserData(-2, "", getDbInfo(), getUserId()); + } catch (Exception e) { + //throw new RaptorRuntimeException(e); + } + + lookup.trimToSize(); + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + if(value != null && value.getId() != null && value.getName() != null ) { + fieldDefValue = nvl(value.getId()); + if (fieldValue != null && fieldValue.equals(value.getId())) { + fieldDefDisplay = nvl(value.getName()); + break; + } + else { + fieldDefValue = ""; + fieldDefDisplay = ""; + } + } + } + if (fieldDefDisplay == null || fieldDefDisplay.length()<=0) { + fieldDefDisplay = nvl(fieldDefValue); + } + + + + //----- END ---// + + + if(getFieldDefaultSQL()!=null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.length()<=0)) { + fieldDefValue = nvl((idNamevalue!=null)?idNamevalue.getId():""); + fieldDefDisplay = nvl((idNamevalue!=null)?idNamevalue.getName():""); + } else { + if(fieldValue == null || fieldValue.trim().equalsIgnoreCase("null")|| fieldValue.length()<=0) fieldValue=""; + fieldDefValue = nvl(fieldDefValue); + fieldDefDisplay = nvl(fieldDefDisplay); + } + + } + } else { + lookup.trimToSize(); + for (lookup.resetNext(); lookup.hasNext();) { + IdNameValue value = lookup.getNext(); + if(value != null && value.getId() != null && value.getName() != null ) { + fieldDefValue = nvl(value.getId()); + if (fieldValue != null && fieldValue.equals(value.getId())) { + fieldDefDisplay = nvl(value.getName()); + break; + } + else { + fieldDefValue = ""; + fieldDefDisplay = ""; + } + } + } + if (fieldDefDisplay == null || fieldDefDisplay.length()<=0) { + fieldDefDisplay = nvl(fieldDefValue); + } + } + }catch(Exception e) { //throw new RaptorRuntimeException(e); + } + + if(!hasPredefinedList) { + if(oldSQL != null && !oldSQL.equals("")) { + ((IdNameSql)lookup).setSQL(oldSQL); + } + } + + if(isVisible()) { + /* return "\n" + " \"Loading, "; + + return progress+" \n  \n" + + " 0) { + valueSQL = lu.getSql(); + avail_ReadOnly = (valueSQL.toLowerCase().indexOf(readOnlyInSql)!=-1); + //System.out.println("OLD SQL TEXT" + valueSQL); + //oldSQL = lu.getSql(); + if(formValues != null) { + Set set = formValues.entrySet(); + String value1 = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + value1 = (String) entry.getValue(); + if (value1.length() <=0) { + value1 = "NULL"; + valueSQL = Utils.replaceInString(valueSQL, "'["+entry.getKey()+"]'", value1); + valueSQL = Utils.replaceInString(valueSQL, "["+entry.getKey()+"]", value1); + } else { + valueSQL = Utils.replaceInString(valueSQL, "["+entry.getKey()+"]", value1); + } + } + // should be value one. + //lookup = new IdNameSql(-1,valueSQL,lu.getDefaultSQL()); + } + } + //lookupList = lookup; + //System.out.println("8888888 88 " + valueSQL); + } + if(valueSQL!=null && valueSQL.length()>0) { + DataSet ds = ConnectionUtils.getDataSet(valueSQL.toString(), dbInfo); + strValue = ds.getString(0,1); + if(avail_ReadOnly) readOnly = ds.getString(0, 2).toUpperCase().startsWith("Y")||ds.getString(0, 2).toUpperCase().startsWith("T");; + } + }catch(Exception e) { //throw new RaptorRuntimeException(e); + } + String returnString = ""; + String timestamp ="", timestamphr = "", timestampmin = "", timestampsec = ""; + + returnString = "0 && (!(fieldValue.toUpperCase().indexOf("SELECT ")!= -1 && fieldValue.toUpperCase().indexOf("FROM")!= -1)) ) { + if(validationType.startsWith("TIMESTAMP")) { + returnString += nvl((fieldValue!=null)?fieldValue.split(" ")[0]:""); + if(fieldValue!=null && fieldValue.length()>0) { + timestamp = (fieldValue.split(" ").length > 1)?fieldValue.split(" ")[1]:""; + String timestampArr[] = timestamp.split(":"); + if((timestampArr.length == 1) || (timestampArr.length == 2) || (timestampArr.length == 3)) + timestamphr = timestampArr[0]; + if((timestampArr.length == 2) || (timestampArr.length == 3)) + timestampmin = timestampArr[1]; + if(timestampArr.length == 3) + timestampsec = timestampArr[2]; + } + + } else returnString += fieldValue; + + } else if(getFieldDefaultSQL()!=null) { + + if(validationType.startsWith("TIMESTAMP")) { + returnString += nvl((strValue.length()>0)?strValue.split(" ")[0]:""); + if(strValue.length()>0) { + timestamp = (strValue.split(" ").length > 1)?strValue.split(" ")[1]:""; + String timestampArr[] = timestamp.split(":"); + if((timestampArr.length == 1) || (timestampArr.length == 2) || (timestampArr.length == 3)) + timestamphr = timestampArr[0]; + if((timestampArr.length == 2) || (timestampArr.length == 3)) + timestampmin = timestampArr[1]; + if(timestampArr.length == 3) + timestampsec = timestampArr[2]; + } + + } else if (nvl(strValue).length()>0) { + returnString += strValue; + } else + returnString += nvl((value!=null)?value.getId():""); + } else if (nvl(strValue).length()>0) { + returnString += strValue; + } else + returnString += nvl((value!=null)?value.getId():""); + + + /*returnString += "\">" + + (validationType.equals(VT_DATE) ? "\n\t\t\t" + + "\n\t\t\t\t" + : ""); */ + + SimpleDateFormat dtf = new SimpleDateFormat("MM/dd/yyyy"); + String stRangeText = this.getRangeStartDate() == null ? null : dtf.format(this.getRangeStartDate().getTime()); + String endRangeText = this.getRangeEndDate() == null ? null : dtf.format(this.getRangeEndDate().getTime()); + ///////////////////////// + + //get the date sqls + + //System.out.println("////////////start range date before Start" + this.getRangeStartDateSQL()); + + if (this.getRangeStartDateSQL() != null && this.getRangeStartDateSQL().trim().toLowerCase().startsWith("select")){ + //System.out.println("////////////start range date Starting"); + String SQL = this.getRangeStartDateSQL(); + if(formValues != null) { + Set set = formValues.entrySet(); + String v = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + v = (String) entry.getValue(); + //System.out.println("///////// key is " + entry.getKey() + " = " + v); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", v); + } + + } + //System.out.println("////////////start range date sql created" + SQL); + try{ + DataSet ds = ConnectionUtils.getDataSet(SQL.toString(), dbInfo); + //System.out.println("////////////start range date is : " + ds.get(0)); + dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar tStart = Calendar.getInstance(); + tStart.setTime(dtf.parse(ds.getString(0,0))); + dtf = new SimpleDateFormat("MM/dd/yyyy"); + stRangeText = dtf.format(tStart.getTime().getTime()-MILLIS_IN_DAY); + + }catch(Exception e){ + System.out.println("Exception////////// : start range date is : " + e); + } + } + + if (this.getRangeEndDateSQL() != null && this.getRangeEndDateSQL().trim().toLowerCase().startsWith("select")){ + //System.out.println("////////////end range date Starting"); + String SQL = this.getRangeEndDateSQL(); + if(formValues != null) { + Set set = formValues.entrySet(); + String v = ""; + for(Iterator iter = set.iterator(); iter.hasNext(); ) { + Map.Entry entry = (Entry) iter.next(); + v = (String) entry.getValue(); + SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", v); + } + + } + try{ + DataSet ds = ConnectionUtils.getDataSet(SQL.toString(), dbInfo); + //System.out.println("////////////end range date is : " + ds.get(0)); + dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar tStart = Calendar.getInstance(); + tStart.setTime(dtf.parse(ds.getString(0,0))); + dtf = new SimpleDateFormat("MM/dd/yyyy"); + //endRangeText = dtf.format(tStart.getTime()); + endRangeText = dtf.format(tStart.getTime().getTime()+MILLIS_IN_DAY); + }catch(Exception e){ + System.out.println("Exception////////// : end range date is : " + e); + } + } + + + ////////////////////// + String calendarOnClickMethodCall = ""; + String timeStampStr = ""; + if (stRangeText == null || endRangeText == null) + calendarOnClickMethodCall = "'oCalendar.select(document." + HTML_FORM + "." + fieldName + ", event,\""+ Globals.getCalendarOutputDateFormat() +"\"); return false;'"; + else + calendarOnClickMethodCall = "'oCalendar=new CalendarPopup(\"calendarDiv\", \"calendarFrame\");oCalendar.setCssPrefix(\"raptor\");oCalendar.addDisabledDates(null, \"" + stRangeText + "\"); oCalendar.addDisabledDates(\"" + endRangeText + "\", null); oCalendar.select(document." + HTML_FORM + "." + fieldName + ", event,\""+ Globals.getCalendarOutputDateFormat() +"\"); return false;'"; + returnString += "\" " + getHelpLink(fieldName) + + (validationType.equals(VT_DATE) || validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC) + ? "\n\t\t\t" + : ""); + if(validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC) ) { + //Add Hours/Minutes and Seconds. + timeStampStr = " Hour "; + } + //Minutes + if( validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC) ) { + int minutes = 0; + int t_min = 0; + try { + minutes = Integer.parseInt(nvl(rr.getParamValue(fieldName+"_Min"),"0")); + if(minutes == 0) { + if(inSchedule) minutes = Integer.parseInt(nvl(((String)formValues.get(fieldName+"_Min")),"0")); + } + } catch (NumberFormatException ex) {minutes = 0;} + try { + t_min = Integer.parseInt(timestampmin); + } catch (NumberFormatException ex) { t_min = 0;} + + if(minutes <= 0) minutes = t_min; + /*if (formValues.containsKey(fieldDisplayName+"_Min")){ + formValues.remove(fieldDisplayName+"_Min"); + formValues.put(fieldDisplayName+"_Min", minutes); + } else + formValues.put(fieldDisplayName+"_Min", minutes); + */ + timeStampStr += " Min "; + } + //Seconds + if( validationType.equals(VT_TIMESTAMP_SEC) ) { + int seconds = 0; + int t_sec = 0; + try { + seconds = Integer.parseInt(nvl(rr.getParamValue(fieldName+"_Sec"),"0")); + if(seconds == 0) { + if(inSchedule) seconds = Integer.parseInt(nvl(((String)formValues.get(fieldName+"_Sec")),"0")); + } + } catch (NumberFormatException ex) {seconds = 0;} + try { + t_sec = Integer.parseInt(timestampsec); + } catch (NumberFormatException ex) { t_sec = 0;} + + if(seconds <= 0) seconds = t_sec; + /*if (formValues.containsKey(fieldDisplayName+"_Sec")){ + formValues.remove(fieldDisplayName+"_Sec"); + formValues.put(fieldDisplayName+"_Sec", seconds); + } else + formValues.put(fieldDisplayName+"_Sec", seconds); + */ + timeStampStr += " Sec "; + } + + returnString += timeStampStr; + String checkboxStr = ""; + if(inSchedule && (validationType.equals(VT_DATE) || validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) ) { + if(!Globals.isScheduleDateParamAutoIncr()) { + checkboxStr = /*checkboxStr +" "+ */ ""; + } else { + checkboxStr = /*checkboxStr +" "+ */""; + } + /*if(validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) { + checkboxStr = checkboxStr +" "+ ""; + } + if(validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) { + checkboxStr = checkboxStr +" "+ ""; + } + if(validationType.equals(VT_TIMESTAMP_SEC)) { + checkboxStr = checkboxStr +" "+ ""; + }*/ + } + if(isVisible()) + return returnString+checkboxStr; + else return ""; + } else if (fieldType.equals(FFT_TEXTAREA)) { + + if(nvl(fieldValue).length()>0) { + fieldValue = Pattern.compile("(^[\r\n])|\\([\\']", Pattern.DOTALL).matcher(fieldValue).replaceAll(""); + fieldValue = Pattern.compile("[\\']\\)", Pattern.DOTALL).matcher(fieldValue).replaceAll(""); + fieldValue = fieldValue.replaceAll("','",","); // changed from "|" + fieldValue = fieldValue.replaceAll("' , '","\r\n"); + } + + if(isVisible()) + return "